Coverage Report

Created: 2026-07-16 06:50

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
        #error "No cipher suites defined because DH disabled, ECC disabled, " \
54
               "and no static suites defined. Please see top of README"
55
    #endif
56
    #ifdef WOLFSSL_CERT_GEN
57
        /* need access to Cert struct for creating certificate */
58
        #include <wolfssl/wolfcrypt/asn_public.h>
59
    #endif
60
#endif
61
62
#if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA)     \
63
    || defined(OPENSSL_EXTRA_X509_SMALL)                    \
64
    || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
65
    #include <wolfssl/openssl/evp.h>
66
    /* openssl headers end, wolfssl internal headers next */
67
#endif
68
69
#include <wolfssl/wolfcrypt/wc_encrypt.h>
70
71
#ifndef NO_RSA
72
    #include <wolfssl/wolfcrypt/rsa.h>
73
#endif
74
75
#ifdef OPENSSL_EXTRA
76
    /* openssl headers begin */
77
    #include <wolfssl/openssl/ssl.h>
78
    #include <wolfssl/openssl/aes.h>
79
#ifndef WOLFCRYPT_ONLY
80
    #include <wolfssl/openssl/hmac.h>
81
    #include <wolfssl/openssl/cmac.h>
82
#endif
83
    #include <wolfssl/openssl/crypto.h>
84
    #include <wolfssl/openssl/des.h>
85
    #include <wolfssl/openssl/bn.h>
86
    #include <wolfssl/openssl/buffer.h>
87
    #include <wolfssl/openssl/dh.h>
88
    #include <wolfssl/openssl/rsa.h>
89
    #include <wolfssl/openssl/fips_rand.h>
90
    #include <wolfssl/openssl/pem.h>
91
    #include <wolfssl/openssl/ec.h>
92
    #include <wolfssl/openssl/ec25519.h>
93
    #include <wolfssl/openssl/ed25519.h>
94
    #include <wolfssl/openssl/ec448.h>
95
    #include <wolfssl/openssl/ed448.h>
96
    #include <wolfssl/openssl/ecdsa.h>
97
    #include <wolfssl/openssl/ecdh.h>
98
    #include <wolfssl/openssl/err.h>
99
    #include <wolfssl/openssl/modes.h>
100
    #include <wolfssl/openssl/opensslv.h>
101
    #include <wolfssl/openssl/rc4.h>
102
    #include <wolfssl/openssl/stack.h>
103
    #include <wolfssl/openssl/x509_vfy.h>
104
    /* openssl headers end, wolfssl internal headers next */
105
    #include <wolfssl/wolfcrypt/hmac.h>
106
    #include <wolfssl/wolfcrypt/random.h>
107
    #include <wolfssl/wolfcrypt/des3.h>
108
    #include <wolfssl/wolfcrypt/ecc.h>
109
    #include <wolfssl/wolfcrypt/md4.h>
110
    #include <wolfssl/wolfcrypt/md5.h>
111
    #include <wolfssl/wolfcrypt/arc4.h>
112
    #include <wolfssl/wolfcrypt/curve25519.h>
113
    #include <wolfssl/wolfcrypt/ed25519.h>
114
    #include <wolfssl/wolfcrypt/curve448.h>
115
    #if defined(HAVE_FALCON)
116
        #include <wolfssl/wolfcrypt/falcon.h>
117
    #endif /* HAVE_FALCON */
118
    #if defined(WOLFSSL_HAVE_MLDSA)
119
        #include <wolfssl/wolfcrypt/wc_mldsa.h>
120
    #endif /* WOLFSSL_HAVE_MLDSA */
121
    #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
122
        #ifdef HAVE_OCSP
123
            #include <wolfssl/openssl/ocsp.h>
124
        #endif
125
        #include <wolfssl/openssl/lhash.h>
126
        #include <wolfssl/openssl/txt_db.h>
127
    #endif /* WITH_STUNNEL */
128
    #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
129
        #include <wolfssl/wolfcrypt/sha512.h>
130
    #endif
131
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
132
        && !defined(WC_NO_RNG)
133
        #include <wolfssl/wolfcrypt/srp.h>
134
    #endif
135
#endif
136
137
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
138
    #include <wolfssl/openssl/x509v3.h>
139
    int wolfssl_bn_get_value(WOLFSSL_BIGNUM* bn, mp_int* mpi);
140
    int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi);
141
#endif
142
143
#if defined(WOLFSSL_QT)
144
    #include <wolfssl/wolfcrypt/sha.h>
145
#endif
146
147
#ifdef NO_ASN
148
    #include <wolfssl/wolfcrypt/dh.h>
149
#endif
150
#endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
151
152
#if !defined(WOLFCRYPT_ONLY) && defined(WOLFSSL_SYS_CRYPTO_POLICY)
153
/* The system wide crypto-policy. Configured by wolfSSL_crypto_policy_enable.
154
 * */
155
static struct SystemCryptoPolicy crypto_policy;
156
#endif /* !WOLFCRYPT_ONLY && WOLFSSL_SYS_CRYPTO_POLICY */
157
158
/*
159
 * ssl.c Build Options:
160
 *
161
 * See also: tls.c for TLS extension/protocol options, tls13.c for TLS 1.3,
162
 *           internal.c for handshake internals, wc_port.c for platform/memory.
163
 *
164
 * OpenSSL Compatibility:
165
 * OPENSSL_EXTRA:              Enable OpenSSL compatibility API        default: off
166
 * OPENSSL_ALL:                Enable all OpenSSL compat APIs          default: off
167
 * OPENSSL_EXTRA_X509_SMALL:   Minimal OpenSSL X509 compat APIs       default: off
168
 * OPENSSL_EXTRA_NO_ASN1:      OpenSSL extra without ASN1 objects      default: off
169
 * OPENSSL_COMPATIBLE_DEFAULTS:
170
 *                  Default behavior compatible with OpenSSL           default: off
171
 * NO_WOLFSSL_STUB:            Disable stubs for unimplemented funcs   default: off
172
 * WOLFSSL_DEBUG_OPENSSL:      Debug logging for OpenSSL compat layer  default: off
173
 * WOLFSSL_HAVE_ERROR_QUEUE:   OpenSSL-compatible error queue          default: off
174
 * WOLFSSL_ERROR_CODE_OPENSSL: Use OpenSSL-compatible error codes      default: off
175
 * WOLFSSL_CIPHER_INTERNALNAME:
176
 *                  Use wolfSSL internal cipher suite names             default: off
177
 * NO_CIPHER_SUITE_ALIASES:    Disable cipher suite name aliases       default: off
178
 * WOLFSSL_SET_CIPHER_BYTES:   Set cipher suites by raw byte values    default: off
179
 * WOLFSSL_OLD_SET_CURVES_LIST:
180
 *                  Old-style curve list parsing for compat             default: off
181
 * WOLFSSL_NO_OPENSSL_RAND_CB: Disable OpenSSL RAND callback compat   default: off
182
 * NO_ERROR_STRINGS:           Disable human-readable error strings    default: off
183
 * WOLFSSL_PUBLIC_ASN:         Make ASN parsing functions public        default: off
184
 *
185
 * Extra Data / BIO:
186
 * HAVE_EX_DATA:               Enable ex_data on SSL/CTX/X509 objects  default: off
187
 * HAVE_EX_DATA_CLEANUP_HOOKS: Cleanup callbacks for ex_data           default: off
188
 * HAVE_EX_DATA_CRYPTO:        ex_data support for wolfCrypt objects   default: off
189
 * MAX_EX_DATA:                Max ex_data entries per object           default: 5
190
 * NO_BIO:                     Disable BIO abstraction layer           default: off
191
 *
192
 * Session & Cache:
193
 * NO_SESSION_CACHE:           Disable server session cache            default: off
194
 * NO_SESSION_CACHE_REF:       wolfSSL_get_session returns ssl->session
195
 *                             reference instead of ClientCache ref    default: off
196
 * SESSION_CACHE_DYNAMIC_MEM:  Dynamically allocate session cache      default: off
197
 * NO_CLIENT_CACHE:            Disable client-side session cache       default: off
198
 * SESSION_CERTS:              Store full cert chain in session         default: off
199
 * WOLFSSL_SESSION_ID_CTX:     Session ID context for cache sharing    default: off
200
 *
201
 * I/O & Transport:
202
 * USE_WOLFSSL_IO:             Use built-in I/O callbacks              default: on
203
 * WOLFSSL_USER_IO:            Application provides custom I/O         default: off
204
 * WOLFSSL_NO_SOCK:            Build without socket support            default: off
205
 * NO_WRITEV:                  Disable writev() scatter/gather I/O     default: off
206
 * WOLFSSL_DTLS_MTU:           Enable DTLS MTU management APIs         default: off
207
 * WOLFSSL_DTLS_DROP_STATS:    Track DTLS packet drop statistics       default: off
208
 * WOLFSSL_MULTICAST:          Enable DTLS multicast support           default: off
209
 *
210
 * Callbacks & Features:
211
 * WOLFSSL_CHECK_ALERT_ON_ERR: Check alerts on handshake error         default: off
212
 * ATOMIC_USER:                User-defined record layer callbacks      default: off
213
 * HAVE_WRITE_DUP:             Separate threads for SSL read/write     default: off
214
 * WOLFSSL_CALLBACKS:          Handshake monitoring callbacks           default: off
215
 * NO_HANDSHAKE_DONE_CB:       Disable handshake completion callback   default: off
216
 * WOLFSSL_SHUTDOWNONCE:       Send close_notify only once             default: off
217
 * WOLFSSL_COPY_CERT:          Copy certificate buffer (own copy)      default: off
218
 * WOLFSSL_COPY_KEY:           Copy private key buffer (own copy)      default: off
219
 * WOLF_PRIVATE_KEY_ID:        Reference private keys by ID            default: off
220
 * WOLFSSL_REFCNT_ERROR_RETURN:
221
 *                  Return errors on ref counting failures             default: off
222
 * WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST:
223
 *                  Allow runtime max fragment size adjustment          default: off
224
 * WOLFSSL_ALLOW_NO_SUITES:    Allow SSL objects with no cipher suites default: off
225
 *
226
 * Certificates & Keys:
227
 * KEEP_PEER_CERT:             Keep peer cert after handshake          default: off
228
 * KEEP_OUR_CERT:              Keep our cert after handshake           default: off
229
 * WOLFSSL_STATIC_RSA:         Enable static RSA key exchange          default: off
230
 * WOLFSSL_HAVE_CERT_SERVICE:  Certificate service callbacks           default: off
231
 * WOLFSSL_SYS_CA_CERTS:       Load system CA certs from OS            default: off
232
 *
233
 * Application Compatibility:
234
 * HAVE_CURL:                  APIs for libcurl compatibility          default: off
235
 * HAVE_LIGHTY:                APIs for lighttpd compatibility         default: off
236
 * HAVE_MEMCACHED:             APIs for memcached compatibility        default: off
237
 * WOLFSSL_APACHE_HTTPD:       APIs for Apache httpd compatibility     default: off
238
 * WOLFSSL_NGINX:              APIs for nginx compatibility            default: off
239
 * WOLFSSL_HAPROXY:            APIs for HAProxy compatibility          default: off
240
 * WOLFSSL_ASIO:               APIs for Boost.Asio compatibility       default: off
241
 * WOLFSSL_PYTHON:             APIs for Python module compatibility    default: off
242
 * WOLFSSL_QT:                 APIs for Qt framework compatibility     default: off
243
 * WOLFSSL_JNI:                APIs for Java JNI/JSSE compatibility    default: off
244
 *
245
 * Protocol Features:
246
 * WOLFSSL_HAVE_WOLFSCEP:      Enable wolfSCEP protocol support        default: off
247
 * WOLFCRYPT_HAVE_SRP:         Enable SRP protocol support             default: off
248
 * HAVE_LIBZ:                  Enable zlib TLS compression             default: off
249
 * WOLFSSL_EXTRA:              Extra SSL session info APIs              default: off
250
 * WOLFSSL_WPAS_SMALL:         Minimal wpa_supplicant/hostapd APIs     default: off
251
 * HAVE_FUZZER:                Fuzzing callback support                 default: off
252
 *
253
 * Memory & Threading:
254
 * WOLFSSL_STATIC_MEMORY_LEAN: Lean static memory allocation           default: off
255
 * WOLFSSL_THREADED_CRYPT:     Multi-threaded crypto operations         default: off
256
 * WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS:
257
 *                  Thread-safe cleanup via atomics                     default: off
258
 * WOLFSSL_ATOMIC_INITIALIZER: Static init for atomic variables        default: off
259
 * WOLFSSL_DEBUG_MEMORY:       Log malloc/free with file/line info     default: off
260
 * WOLFSSL_NO_REALLOC:         Disable realloc, use malloc+copy+free   default: off
261
 * WOLFSSL_HEAP_TEST:          Heap-related testing utilities           default: off
262
 *
263
 * Debugging & Build:
264
 * SHOW_SIZES:                 Display struct sizes at init             default: off
265
 * WOLFSSL_DEBUG_TRACE_ERROR_CODES:
266
 *                  Trace error code origins for debugging              default: off
267
 * HAVE_ATEXIT:                Register wolfSSL_Cleanup via atexit     default: off
268
 * WOLFSSL_SYS_CRYPTO_POLICY:  Honor system crypto policy settings     default: off
269
 *
270
 * Hardware TLS:
271
 * WOLFSSL_RENESAS_TSIP_TLS:   Renesas TSIP hardware crypto for TLS   default: off
272
 * WOLFSSL_RENESAS_FSPSM_TLS:  Renesas FSP Security Module for TLS    default: off
273
 * WOLFSSL_EGD_NBLOCK:         Non-blocking EGD entropy support        default: off
274
 */
275
276
#define WOLFSSL_SSL_MISC_INCLUDED
277
#include "src/ssl_misc.c"
278
279
#define WOLFSSL_EVP_INCLUDED
280
#include "wolfcrypt/src/evp.c"
281
282
/* Crypto code uses EVP APIs. */
283
#define WOLFSSL_SSL_CRYPTO_INCLUDED
284
#include "src/ssl_crypto.c"
285
286
#ifndef WOLFCRYPT_ONLY
287
#define WOLFSSL_SSL_CERTMAN_INCLUDED
288
#include "src/ssl_certman.c"
289
290
#define WOLFSSL_SSL_SESS_INCLUDED
291
#include "src/ssl_sess.c"
292
293
#define WOLFSSL_SSL_API_CERT_INCLUDED
294
#include "src/ssl_api_cert.c"
295
296
#define WOLFSSL_SSL_API_PK_INCLUDED
297
#include "src/ssl_api_pk.c"
298
#endif
299
300
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
301
    !defined(WOLFCRYPT_ONLY)
302
/* Convert shortname to NID.
303
 *
304
 * For OpenSSL compatibility.
305
 *
306
 * @param [in] sn  Short name of OID.
307
 * @return  NID corresponding to shortname on success.
308
 * @return  WC_NID_undef when not recognized.
309
 */
310
int wc_OBJ_sn2nid(const char *sn)
311
{
312
    const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
313
    size_t i;
314
    WOLFSSL_ENTER("wc_OBJ_sn2nid");
315
    for (i = 0; i < wolfssl_object_info_sz; i++, obj_info++) {
316
        if (XSTRCMP(sn, obj_info->sName) == 0)
317
            return obj_info->nid;
318
    }
319
    WOLFSSL_MSG("short name not found in table");
320
    return WC_NID_undef;
321
}
322
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
323
324
#ifndef WOLFCRYPT_ONLY
325
326
327
#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \
328
    (defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && !defined(NO_DSA))
329
330
#define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
331
static WC_RNG globalRNG;
332
static volatile int initGlobalRNG = 0;
333
334
#if defined(OPENSSL_EXTRA) || !defined(WOLFSSL_MUTEX_INITIALIZER)
335
static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex
336
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex);
337
#endif
338
#ifndef WOLFSSL_MUTEX_INITIALIZER
339
static int globalRNGMutex_valid = 0;
340
#endif
341
342
#if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
343
static WOLFSSL_DRBG_CTX* gDrbgDefCtx = NULL;
344
#endif
345
346
WC_RNG* wolfssl_get_global_rng(void)
347
0
{
348
0
    WC_RNG* ret = NULL;
349
350
0
    if (initGlobalRNG == 0)
351
0
        WOLFSSL_MSG("Global RNG no Init");
352
0
    else
353
0
        ret = &globalRNG;
354
355
0
    return ret;
356
0
}
357
358
/* Make a global RNG and return.
359
 *
360
 * @return  Global RNG on success.
361
 * @return  NULL on error.
362
 */
363
WC_RNG* wolfssl_make_global_rng(void)
364
0
{
365
0
    WC_RNG* ret;
366
367
0
#ifdef HAVE_GLOBAL_RNG
368
    /* Get the global random number generator instead. */
369
0
    ret = wolfssl_get_global_rng();
370
#ifdef OPENSSL_EXTRA
371
    if (ret == NULL) {
372
        /* Create a global random if possible. */
373
        (void)wolfSSL_RAND_Init();
374
        ret = wolfssl_get_global_rng();
375
    }
376
#endif
377
#else
378
    WOLFSSL_ERROR_MSG("Bad RNG Init");
379
    ret = NULL;
380
#endif
381
382
0
    return ret;
383
0
}
384
385
/* Too many defines to check explicitly - prototype it and always include
386
 * for RSA, DH, ECC and DSA for BN. */
387
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local);
388
389
/* Make a random number generator or get global if possible.
390
 *
391
 * Global may not be available and NULL will be returned.
392
 *
393
 * @param [in, out] rng    Local random number generator.
394
 * @param [out]     local  Local random number generator returned.
395
 * @return  NULL on failure.
396
 * @return  A random number generator object.
397
 */
398
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local)
399
0
{
400
0
    WC_RNG* ret = NULL;
401
#ifdef WOLFSSL_SMALL_STACK
402
    int freeRng = 0;
403
404
    /* Allocate RNG object . */
405
    if (rng == NULL) {
406
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
407
        freeRng = 1;
408
    }
409
#endif
410
411
0
    if (rng != NULL) {
412
0
        if (wc_InitRng(rng) == 0) {
413
0
            ret = rng;
414
0
            *local = 1;
415
0
        }
416
0
        else {
417
0
            WOLFSSL_MSG("Bad RNG Init");
418
#ifdef WOLFSSL_SMALL_STACK
419
            if (freeRng) {
420
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
421
                rng = NULL;
422
            }
423
#endif
424
0
        }
425
0
    }
426
0
    if (ret == NULL) {
427
0
#ifdef HAVE_GLOBAL_RNG
428
0
        WOLFSSL_MSG("trying global RNG");
429
0
#endif
430
0
        ret = wolfssl_make_global_rng();
431
0
    }
432
433
0
    return ret;
434
0
}
435
#endif
436
437
#ifdef OPENSSL_EXTRA
438
    /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
439
     *                OPENSSL_EXTRA where RAND callbacks are not used */
440
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
441
        static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
442
        static wolfSSL_Mutex gRandMethodMutex
443
            WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex);
444
        #ifndef WOLFSSL_MUTEX_INITIALIZER
445
        static int gRandMethodsInit = 0;
446
        #endif
447
    #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
448
#endif /* OPENSSL_EXTRA */
449
450
#define WOLFSSL_SSL_BN_INCLUDED
451
#include "src/ssl_bn.c"
452
453
#ifndef OPENSSL_EXTRA_NO_ASN1
454
#define WOLFSSL_SSL_ASN1_INCLUDED
455
#include "src/ssl_asn1.c"
456
#endif /* OPENSSL_EXTRA_NO_ASN1 */
457
458
#define WOLFSSL_SSL_TSP_INCLUDED
459
#include "src/ssl_tsp.c"
460
461
#define WOLFSSL_PK_INCLUDED
462
#include "src/pk.c"
463
464
#define WOLFSSL_EVP_PK_INCLUDED
465
#include "wolfcrypt/src/evp_pk.c"
466
467
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
468
/* copies over data of "in" to "out" */
469
static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out)
470
{
471
    if (in == NULL || out == NULL)
472
        return;
473
474
    *out = *in;
475
}
476
477
478
#if defined(OPENSSL_ALL)
479
static WOLFSSL_X509_OBJECT* wolfSSL_X509_OBJECT_dup(WOLFSSL_X509_OBJECT* obj)
480
{
481
    WOLFSSL_X509_OBJECT* ret = NULL;
482
    if (obj) {
483
        ret = wolfSSL_X509_OBJECT_new();
484
        if (ret) {
485
            ret->type = obj->type;
486
            switch (ret->type) {
487
                case WOLFSSL_X509_LU_NONE:
488
                    break;
489
                case WOLFSSL_X509_LU_X509:
490
                    ret->data.x509 = wolfSSL_X509_dup(obj->data.x509);
491
                    break;
492
                case WOLFSSL_X509_LU_CRL:
493
            #if defined(HAVE_CRL)
494
                    ret->data.crl = wolfSSL_X509_CRL_dup(obj->data.crl);
495
            #endif
496
                    break;
497
            }
498
        }
499
    }
500
    return ret;
501
}
502
#endif /* OPENSSL_ALL */
503
504
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
505
506
#define WOLFSSL_SSL_SK_INCLUDED
507
#include "src/ssl_sk.c"
508
509
510
#include <wolfssl/wolfcrypt/hpke.h>
511
512
#define WOLFSSL_SSL_ECH_INCLUDED
513
#include "src/ssl_ech.c"
514
515
#ifdef OPENSSL_EXTRA
516
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
517
        Suites* suites, const char* list);
518
#endif
519
520
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
521
#include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
522
#endif
523
524
/* prevent multiple mutex initializations */
525
526
/* note, initRefCount is not used for thread synchronization, only for
527
 * bookkeeping while inits_count_mutex is held.
528
 */
529
static volatile WC_THREADSHARED int initRefCount = 0;
530
531
/* init ref count mutex */
532
static WC_THREADSHARED wolfSSL_Mutex inits_count_mutex
533
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex);
534
#ifndef WOLFSSL_MUTEX_INITIALIZER
535
static WC_THREADSHARED volatile int inits_count_mutex_valid = 0;
536
#endif
537
538
#ifdef NO_TLS
539
static const WOLFSSL_METHOD gNoTlsMethod;
540
#endif
541
542
/* Create a new WOLFSSL_CTX struct and return the pointer to created struct.
543
   WOLFSSL_METHOD pointer passed in is given to ctx to manage.
544
   This function frees the passed in WOLFSSL_METHOD struct on failure and on
545
   success is freed when ctx is freed.
546
 */
547
WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap)
548
0
{
549
0
    WOLFSSL_CTX* ctx = NULL;
550
551
0
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
552
553
0
    if (initRefCount == 0) {
554
        /* user no longer forced to call Init themselves */
555
0
        int ret = wolfSSL_Init();
556
0
        if (ret != WOLFSSL_SUCCESS) {
557
0
            WOLFSSL_MSG("wolfSSL_Init failed");
558
0
            WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
559
0
            XFREE(method, heap, DYNAMIC_TYPE_METHOD);
560
0
            return NULL;
561
0
        }
562
0
    }
563
564
0
#ifndef NO_TLS
565
0
    if (method == NULL)
566
0
        return ctx;
567
#else
568
    /* a blank TLS method */
569
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
570
#endif
571
572
0
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
573
0
    if (ctx) {
574
0
        int ret;
575
576
0
        ret = InitSSL_Ctx(ctx, method, heap);
577
    #ifdef WOLFSSL_STATIC_MEMORY
578
        if (heap != NULL) {
579
            ctx->onHeapHint = 1; /* free the memory back to heap when done */
580
        }
581
    #endif
582
0
        if (ret < 0) {
583
0
            WOLFSSL_MSG("Init CTX failed");
584
0
            wolfSSL_CTX_free(ctx);
585
0
            ctx = NULL;
586
0
        }
587
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
588
                           && !defined(NO_SHA256) && !defined(WC_NO_RNG)
589
        else {
590
            ctx->srp = (Srp*)XMALLOC(sizeof(Srp), heap, DYNAMIC_TYPE_SRP);
591
            if (ctx->srp == NULL){
592
                WOLFSSL_MSG("Init CTX failed");
593
                wolfSSL_CTX_free(ctx);
594
                return NULL;
595
            }
596
            XMEMSET(ctx->srp, 0, sizeof(Srp));
597
        }
598
#endif
599
0
    }
600
0
    else {
601
0
        WOLFSSL_MSG("Alloc CTX failed, method freed");
602
0
        XFREE(method, heap, DYNAMIC_TYPE_METHOD);
603
0
    }
604
605
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
606
    if (ctx) {
607
        wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, NULL);
608
        wolfSSL_CTX_set_mode(ctx, WOLFSSL_MODE_AUTO_RETRY);
609
        if (wolfSSL_CTX_set_min_proto_version(ctx,
610
                (method->version.major == DTLS_MAJOR) ?
611
                DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS ||
612
#ifdef HAVE_ANON
613
                wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS ||
614
#endif
615
                wolfSSL_CTX_set_group_messages(ctx) != WOLFSSL_SUCCESS) {
616
            WOLFSSL_MSG("Setting OpenSSL CTX defaults failed");
617
            wolfSSL_CTX_free(ctx);
618
            ctx = NULL;
619
        }
620
    }
621
#endif
622
623
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
624
    /* Load the crypto-policy ciphers if configured. */
625
    if (ctx && wolfSSL_crypto_policy_is_enabled()) {
626
        const char * list = wolfSSL_crypto_policy_get_ciphers();
627
        int          ret = 0;
628
629
        if (list != NULL && *list != '\0') {
630
            if (AllocateCtxSuites(ctx) != 0) {
631
                WOLFSSL_MSG("allocate ctx suites failed");
632
                wolfSSL_CTX_free(ctx);
633
                ctx = NULL;
634
            }
635
            else {
636
                ret = wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
637
                if (ret != WOLFSSL_SUCCESS) {
638
                    WOLFSSL_MSG("parse cipher list failed");
639
                    wolfSSL_CTX_free(ctx);
640
                    ctx = NULL;
641
                }
642
            }
643
        }
644
    }
645
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
646
647
0
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
648
0
    return ctx;
649
0
}
650
651
652
WOLFSSL_ABI
653
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
654
0
{
655
#ifdef WOLFSSL_HEAP_TEST
656
    /* if testing the heap hint then set top level CTX to have test value */
657
    return wolfSSL_CTX_new_ex(method, (void*)WOLFSSL_HEAP_TEST);
658
#else
659
0
    return wolfSSL_CTX_new_ex(method, NULL);
660
0
#endif
661
0
}
662
663
/* increases CTX reference count to track proper time to "free" */
664
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
665
0
{
666
0
    int ret;
667
0
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
668
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
669
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
670
#else
671
0
    (void)ret;
672
0
    return WOLFSSL_SUCCESS;
673
0
#endif
674
0
}
675
676
WOLFSSL_ABI
677
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
678
0
{
679
0
    WOLFSSL_ENTER("wolfSSL_CTX_free");
680
0
    if (ctx) {
681
0
        FreeSSL_Ctx(ctx);
682
0
    }
683
684
0
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
685
0
}
686
687
688
#ifdef HAVE_ENCRYPT_THEN_MAC
689
/**
690
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
691
 * The default value: enabled.
692
 *
693
 * ctx  SSL/TLS context.
694
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
695
 * returns WOLFSSL_SUCCESS
696
 */
697
int wolfSSL_CTX_AllowEncryptThenMac(WOLFSSL_CTX *ctx, int set)
698
0
{
699
0
    ctx->disallowEncThenMac = !set;
700
0
    return WOLFSSL_SUCCESS;
701
0
}
702
703
/**
704
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
705
 * The default value comes from context.
706
 *
707
 * ctx  SSL/TLS context.
708
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
709
 * returns WOLFSSL_SUCCESS
710
 */
711
int wolfSSL_AllowEncryptThenMac(WOLFSSL *ssl, int set)
712
0
{
713
0
    ssl->options.disallowEncThenMac = !set;
714
0
    return WOLFSSL_SUCCESS;
715
0
}
716
#endif
717
718
#ifdef SINGLE_THREADED
719
/* no locking in single threaded mode, allow a CTX level rng to be shared with
720
 * WOLFSSL objects, WOLFSSL_SUCCESS on ok */
721
int wolfSSL_CTX_new_rng(WOLFSSL_CTX* ctx)
722
{
723
    WC_RNG* rng;
724
    int     ret;
725
726
    if (ctx == NULL) {
727
        return BAD_FUNC_ARG;
728
    }
729
730
    rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ctx->heap, DYNAMIC_TYPE_RNG);
731
    if (rng == NULL) {
732
        return MEMORY_E;
733
    }
734
735
#ifndef HAVE_FIPS
736
    ret = wc_InitRng_ex(rng, ctx->heap, ctx->devId);
737
#else
738
    ret = wc_InitRng(rng);
739
#endif
740
    if (ret != 0) {
741
        XFREE(rng, ctx->heap, DYNAMIC_TYPE_RNG);
742
        return ret;
743
    }
744
745
    ctx->rng = rng;
746
    return WOLFSSL_SUCCESS;
747
}
748
#endif
749
750
751
WOLFSSL_ABI
752
WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx)
753
0
{
754
0
    WOLFSSL* ssl = NULL;
755
0
    int ret = 0;
756
757
0
    WOLFSSL_ENTER("wolfSSL_new");
758
759
0
    if (ctx == NULL) {
760
0
        WOLFSSL_MSG("wolfSSL_new ctx is null");
761
0
        return NULL;
762
0
    }
763
764
0
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
765
766
0
    if (ssl == NULL) {
767
0
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
768
0
                        (int)sizeof(WOLFSSL));
769
0
    }
770
0
    else {
771
0
        ret = InitSSL(ssl, ctx, 0);
772
0
        if (ret < 0) {
773
0
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
774
0
            FreeSSL(ssl, ctx->heap);
775
0
            ssl = NULL;
776
0
        }
777
0
        else if (ret == 0) {
778
0
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
779
0
        }
780
0
        else {
781
            /* Only success (0) or negative values should ever be seen. */
782
0
            WOLFSSL_MSG_EX("WARNING: wolfSSL_new unexpected InitSSL return"
783
0
                           " value = %d", ret);
784
0
        } /* InitSSL check */
785
0
    } /* ssl XMALLOC success */
786
787
0
    WOLFSSL_LEAVE("wolfSSL_new InitSSL =", ret);
788
0
    (void)ret;
789
790
0
    return ssl;
791
0
}
792
793
794
WOLFSSL_ABI
795
void wolfSSL_free(WOLFSSL* ssl)
796
0
{
797
0
    WOLFSSL_ENTER("wolfSSL_free");
798
799
0
    if (ssl) {
800
0
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
801
0
        FreeSSL(ssl, ssl->ctx->heap);
802
0
    }
803
0
    else {
804
0
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
805
0
    }
806
0
    WOLFSSL_LEAVE("wolfSSL_free", 0);
807
0
}
808
809
810
int wolfSSL_is_server(WOLFSSL* ssl)
811
0
{
812
0
    if (ssl == NULL)
813
0
        return BAD_FUNC_ARG;
814
0
    return ssl->options.side == WOLFSSL_SERVER_END;
815
0
}
816
817
#ifdef HAVE_WRITE_DUP
818
819
/*
820
 * Release resources around WriteDup object
821
 *
822
 * ssl WOLFSSL object
823
 *
824
 * no return, destruction so make best attempt
825
*/
826
void FreeWriteDup(WOLFSSL* ssl)
827
{
828
    int doFree = 0;
829
830
    WOLFSSL_ENTER("FreeWriteDup");
831
832
    if (ssl->dupWrite) {
833
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) == 0) {
834
            ssl->dupWrite->dupCount--;
835
            if (ssl->dupWrite->dupCount == 0) {
836
                doFree = 1;
837
            } else {
838
                WOLFSSL_MSG("WriteDup count not zero, no full free");
839
            }
840
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
841
        }
842
    }
843
844
    if (doFree) {
845
#ifdef WOLFSSL_DTLS13
846
        struct Dtls13RecordNumber* rn = ssl->dupWrite->sendAckList;
847
        while (rn != NULL) {
848
            struct Dtls13RecordNumber* next = rn->next;
849
            XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
850
            rn = next;
851
        }
852
#endif
853
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
854
        Free_HS_Hashes(ssl->dupWrite->postHandshakeHashState, ssl->heap);
855
        {
856
            CertReqCtx* ctx = ssl->dupWrite->postHandshakeCertReqCtx;
857
            while (ctx != NULL) {
858
                CertReqCtx* nxt = ctx->next;
859
                XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
860
                ctx = nxt;
861
            }
862
        }
863
#endif /* WOLFSSL_TLS13 && WOLFSSL_POST_HANDSHAKE_AUTH */
864
        wc_FreeMutex(&ssl->dupWrite->dupMutex);
865
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
866
        ssl->dupWrite = NULL;
867
        WOLFSSL_MSG("Did WriteDup full free, count to zero");
868
    }
869
}
870
871
872
/*
873
 * duplicate existing ssl members into dup needed for writing
874
 *
875
 * dup write only WOLFSSL
876
 * ssl existing WOLFSSL
877
 *
878
 * 0 on success
879
*/
880
static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
881
{
882
    word16 tmp_weOwnRng;
883
#ifdef HAVE_ONE_TIME_AUTH
884
#ifdef HAVE_POLY1305
885
    Poly1305* tmp_poly1305 = NULL;
886
#endif
887
#endif
888
889
    /* shared dupWrite setup */
890
    ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
891
                                       DYNAMIC_TYPE_WRITEDUP);
892
    if (ssl->dupWrite == NULL) {
893
        return MEMORY_E;
894
    }
895
    XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
896
897
    if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
898
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
899
        ssl->dupWrite = NULL;
900
        return BAD_MUTEX_E;
901
    }
902
903
    /* Pre-allocate any objects that can fail BEFORE performing destructive
904
     * state mutations on ssl, so an allocation failure cannot leave ssl
905
     * with a zeroed encrypt context and a poisoned dupWrite.
906
     * dup->heap == ssl->heap here because dup was initialised with ssl->ctx;
907
     * use ssl->heap consistently for cleanup symmetry. */
908
#ifdef HAVE_ONE_TIME_AUTH
909
#ifdef HAVE_POLY1305
910
    if (ssl->auth.setup && ssl->auth.poly1305 != NULL) {
911
        tmp_poly1305 = (Poly1305*)XMALLOC(sizeof(Poly1305), ssl->heap,
912
            DYNAMIC_TYPE_CIPHER);
913
        if (tmp_poly1305 == NULL) {
914
            wc_FreeMutex(&ssl->dupWrite->dupMutex);
915
            XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
916
            ssl->dupWrite = NULL;
917
            return MEMORY_E;
918
        }
919
    }
920
#endif
921
#endif
922
923
    ssl->dupWrite->dupCount = 2;    /* both sides have a count to start */
924
    dup->dupWrite = ssl->dupWrite; /* each side uses */
925
926
    tmp_weOwnRng = dup->options.weOwnRng;
927
928
    /* copy write parts over to dup writer */
929
    XMEMCPY(&dup->specs,   &ssl->specs,   sizeof(CipherSpecs));
930
    XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
931
    XMEMCPY(&dup->keys,    &ssl->keys,    sizeof(Keys));
932
    XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
933
    XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
934
    XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
935
936
    /* dup side now owns encrypt/write ciphers */
937
    XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
938
939
#ifdef HAVE_ONE_TIME_AUTH
940
#ifdef HAVE_POLY1305
941
    if (tmp_poly1305 != NULL) {
942
        dup->auth.poly1305 = tmp_poly1305;
943
        dup->auth.setup = 1;
944
    }
945
#endif
946
#endif
947
948
#ifdef WOLFSSL_TLS13
949
    if (IsAtLeastTLSv1_3(ssl->version)) {
950
        /* Copy TLS 1.3 application traffic secrets so the write side can
951
         * derive updated keys when wolfSSL_update_keys() is called. */
952
        XMEMCPY(dup->clientSecret, ssl->clientSecret, SECRET_LEN);
953
        XMEMCPY(dup->serverSecret, ssl->serverSecret, SECRET_LEN);
954
955
#ifdef WOLFSSL_DTLS13
956
        if (ssl->options.dtls) {
957
            /* Copy epoch array (contains only value types -- safe to memcpy). */
958
            XMEMCPY(dup->dtls13Epochs, ssl->dtls13Epochs,
959
                    sizeof(ssl->dtls13Epochs));
960
961
            /* Re-point dtls13EncryptEpoch into dup's own epoch array. */
962
            if (ssl->dtls13EncryptEpoch != NULL) {
963
                dup->dtls13EncryptEpoch =
964
                    &dup->dtls13Epochs[ssl->dtls13EncryptEpoch -
965
                                       ssl->dtls13Epochs];
966
            }
967
968
            /* Copy current write epoch number. */
969
            dup->dtls13Epoch = ssl->dtls13Epoch;
970
971
            /* Transfer record-number encryption cipher ownership to dup. */
972
            XMEMCPY(&dup->dtlsRecordNumberEncrypt,
973
                    &ssl->dtlsRecordNumberEncrypt, sizeof(RecordNumberCiphers));
974
            XMEMSET(&ssl->dtlsRecordNumberEncrypt,
975
                    0, sizeof(RecordNumberCiphers));
976
        }
977
#endif /* WOLFSSL_DTLS13 */
978
    }
979
#endif /* WOLFSSL_TLS13 */
980
981
982
    dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
983
    dup->CBIOSend = ssl->CBIOSend;
984
#ifdef OPENSSL_EXTRA
985
    dup->cbioFlag = ssl->cbioFlag;
986
#endif
987
    dup->wfd    = ssl->wfd;
988
    dup->wflags = ssl->wflags;
989
#ifndef WOLFSSL_AEAD_ONLY
990
    dup->hmac   = ssl->hmac;
991
#endif
992
#ifdef HAVE_TRUNCATED_HMAC
993
    dup->truncated_hmac = ssl->truncated_hmac;
994
#endif
995
996
    /* Restore rng option */
997
    dup->options.weOwnRng = tmp_weOwnRng;
998
999
    /* unique side dup setup */
1000
    dup->dupSide = WRITE_DUP_SIDE;
1001
    ssl->dupSide = READ_DUP_SIDE;
1002
1003
    return 0;
1004
}
1005
1006
1007
/*
1008
 * duplicate a WOLFSSL object post handshake for writing only
1009
 * turn existing object into read only.  Allows concurrent access from two
1010
 * different threads.
1011
 *
1012
 * ssl existing WOLFSSL object
1013
 *
1014
 * return dup'd WOLFSSL object on success
1015
*/
1016
WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
1017
{
1018
    WOLFSSL* dup = NULL;
1019
    int ret = 0;
1020
1021
    (void)ret;
1022
    WOLFSSL_ENTER("wolfSSL_write_dup");
1023
1024
    if (ssl == NULL) {
1025
        return ssl;
1026
    }
1027
1028
    if (ssl->options.handShakeDone == 0) {
1029
        WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
1030
        return NULL;
1031
    }
1032
1033
    if (ssl->dupWrite) {
1034
        WOLFSSL_MSG("wolfSSL_write_dup already called once");
1035
        return NULL;
1036
    }
1037
1038
    dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
1039
    if (dup) {
1040
        if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
1041
            FreeSSL(dup, ssl->ctx->heap);
1042
            dup = NULL;
1043
        } else if ( (ret = DupSSL(dup, ssl)) < 0) {
1044
            FreeSSL(dup, ssl->ctx->heap);
1045
            dup = NULL;
1046
        }
1047
    }
1048
1049
    WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
1050
1051
    return dup;
1052
}
1053
1054
1055
/*
1056
 * Notify write dup side of fatal error or close notify
1057
 *
1058
 * ssl WOLFSSL object
1059
 * err Notify err
1060
 *
1061
 * 0 on success
1062
*/
1063
int NotifyWriteSide(WOLFSSL* ssl, int err)
1064
{
1065
    int ret;
1066
1067
    WOLFSSL_ENTER("NotifyWriteSide");
1068
1069
    ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
1070
    if (ret == 0) {
1071
        ssl->dupWrite->dupErr = err;
1072
        ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1073
    }
1074
1075
    return ret;
1076
}
1077
1078
1079
#endif /* HAVE_WRITE_DUP */
1080
1081
1082
#ifdef HAVE_POLY1305
1083
/* set if to use old poly 1 for yes 0 to use new poly */
1084
int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
1085
0
{
1086
0
    (void)ssl;
1087
0
    (void)value;
1088
1089
0
#ifndef WOLFSSL_NO_TLS12
1090
0
    WOLFSSL_ENTER("wolfSSL_use_old_poly");
1091
0
    WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
1092
0
            "is depreciated");
1093
0
    ssl->options.oldPoly = (word16)value;
1094
0
    WOLFSSL_LEAVE("wolfSSL_use_old_poly", 0);
1095
0
#endif
1096
0
    return 0;
1097
0
}
1098
#endif
1099
1100
1101
WOLFSSL_ABI
1102
int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
1103
0
{
1104
0
    int ret;
1105
1106
0
    WOLFSSL_ENTER("wolfSSL_set_fd");
1107
1108
0
    if (ssl == NULL) {
1109
0
        return BAD_FUNC_ARG;
1110
0
    }
1111
1112
0
    ret = wolfSSL_set_read_fd(ssl, fd);
1113
0
    if (ret == WOLFSSL_SUCCESS) {
1114
0
        ret = wolfSSL_set_write_fd(ssl, fd);
1115
0
    }
1116
1117
0
    return ret;
1118
0
}
1119
1120
1121
int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
1122
0
{
1123
0
    WOLFSSL_ENTER("wolfSSL_set_read_fd");
1124
1125
0
    if (ssl == NULL) {
1126
0
        return BAD_FUNC_ARG;
1127
0
    }
1128
1129
0
    ssl->rfd = fd;      /* not used directly to allow IO callbacks */
1130
0
    ssl->IOCB_ReadCtx  = &ssl->rfd;
1131
1132
    #ifdef WOLFSSL_DTLS
1133
        ssl->buffers.dtlsCtx.connected = 0;
1134
        if (ssl->options.dtls) {
1135
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
1136
            ssl->buffers.dtlsCtx.rfd = fd;
1137
        #ifdef USE_WOLFSSL_IO
1138
            ssl->buffers.dtlsCtx.rfdIsDGram =
1139
                (byte)(wolfIO_SockIsDGram(fd) != 0);
1140
        #endif
1141
        }
1142
    #endif
1143
1144
0
    WOLFSSL_LEAVE("wolfSSL_set_read_fd", WOLFSSL_SUCCESS);
1145
0
    return WOLFSSL_SUCCESS;
1146
0
}
1147
1148
1149
int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
1150
0
{
1151
0
    WOLFSSL_ENTER("wolfSSL_set_write_fd");
1152
1153
0
    if (ssl == NULL) {
1154
0
        return BAD_FUNC_ARG;
1155
0
    }
1156
1157
0
    ssl->wfd = fd;      /* not used directly to allow IO callbacks */
1158
0
    ssl->IOCB_WriteCtx  = &ssl->wfd;
1159
1160
    #ifdef WOLFSSL_DTLS
1161
        ssl->buffers.dtlsCtx.connected = 0;
1162
        if (ssl->options.dtls) {
1163
            ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
1164
            ssl->buffers.dtlsCtx.wfd = fd;
1165
        #ifdef USE_WOLFSSL_IO
1166
            ssl->buffers.dtlsCtx.wfdIsDGram =
1167
                (byte)(wolfIO_SockIsDGram(fd) != 0);
1168
        #endif
1169
        }
1170
    #endif
1171
1172
0
    WOLFSSL_LEAVE("wolfSSL_set_write_fd", WOLFSSL_SUCCESS);
1173
0
    return WOLFSSL_SUCCESS;
1174
0
}
1175
1176
1177
/**
1178
  * Get the name of cipher at priority level passed in.
1179
  */
1180
char* wolfSSL_get_cipher_list(int priority)
1181
0
{
1182
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1183
1184
0
    if (priority >= GetCipherNamesSize() || priority < 0) {
1185
0
        return 0;
1186
0
    }
1187
1188
0
    return (char*)ciphers[priority].name;
1189
0
}
1190
1191
1192
/**
1193
  * Get the name of cipher at priority level passed in.
1194
  */
1195
char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
1196
0
{
1197
1198
0
    if (ssl == NULL) {
1199
0
        return NULL;
1200
0
    }
1201
0
    else {
1202
0
        const char* cipher;
1203
1204
0
        if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
1205
0
            if (priority == 0) {
1206
0
                return (char*)cipher;
1207
0
            }
1208
0
            else {
1209
0
                return NULL;
1210
0
            }
1211
0
        }
1212
0
        else {
1213
0
            return wolfSSL_get_cipher_list(priority);
1214
0
        }
1215
0
    }
1216
0
}
1217
1218
1219
int wolfSSL_get_ciphers(char* buf, int len)
1220
0
{
1221
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1222
0
    int ciphersSz = GetCipherNamesSize();
1223
0
    int i;
1224
1225
0
    if (buf == NULL || len <= 0)
1226
0
        return BAD_FUNC_ARG;
1227
1228
    /* Add each member to the buffer delimited by a : */
1229
0
    for (i = 0; i < ciphersSz; i++) {
1230
0
        int cipherNameSz = (int)XSTRLEN(ciphers[i].name);
1231
0
        if (cipherNameSz + 1 < len) {
1232
0
            XSTRNCPY(buf, ciphers[i].name, (size_t)len);
1233
0
            buf += cipherNameSz;
1234
1235
0
            if (i < ciphersSz - 1)
1236
0
                *buf++ = ':';
1237
0
            *buf = 0;
1238
1239
0
            len -= cipherNameSz + 1;
1240
0
        }
1241
0
        else
1242
0
            return BUFFER_E;
1243
0
    }
1244
0
    return WOLFSSL_SUCCESS;
1245
0
}
1246
1247
1248
#ifndef NO_ERROR_STRINGS
1249
/* places a list of all supported cipher suites in TLS_* format into "buf"
1250
 * return WOLFSSL_SUCCESS on success */
1251
int wolfSSL_get_ciphers_iana(char* buf, int len)
1252
0
{
1253
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1254
0
    int ciphersSz = GetCipherNamesSize();
1255
0
    int i;
1256
0
    int cipherNameSz;
1257
1258
0
    if (buf == NULL || len <= 0)
1259
0
        return BAD_FUNC_ARG;
1260
1261
    /* Add each member to the buffer delimited by a : */
1262
0
    for (i = 0; i < ciphersSz; i++) {
1263
0
#ifndef NO_CIPHER_SUITE_ALIASES
1264
0
        if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
1265
0
            continue;
1266
0
#endif
1267
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
1268
0
        if (cipherNameSz + 1 < len) {
1269
0
            XSTRNCPY(buf, ciphers[i].name_iana, (size_t)len);
1270
0
            buf += cipherNameSz;
1271
1272
0
            if (i < ciphersSz - 1)
1273
0
                *buf++ = ':';
1274
0
            *buf = 0;
1275
1276
0
            len -= cipherNameSz + 1;
1277
0
        }
1278
0
        else
1279
0
            return BUFFER_E;
1280
0
    }
1281
0
    return WOLFSSL_SUCCESS;
1282
0
}
1283
#endif /* NO_ERROR_STRINGS */
1284
1285
1286
const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
1287
0
{
1288
0
    const char* cipher;
1289
1290
0
    if (ssl == NULL || buf == NULL || len <= 0)
1291
0
        return NULL;
1292
1293
0
    cipher = wolfSSL_get_cipher_name_iana(ssl);
1294
0
    if (cipher == NULL)
1295
0
        return NULL;
1296
0
    len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1));
1297
0
    XMEMCPY(buf, cipher, (size_t)len);
1298
0
    return buf;
1299
0
}
1300
1301
int wolfSSL_get_fd(const WOLFSSL* ssl)
1302
0
{
1303
0
    int fd = -1;
1304
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1305
0
    if (ssl) {
1306
0
        fd = ssl->rfd;
1307
0
    }
1308
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1309
0
    return fd;
1310
0
}
1311
1312
int wolfSSL_get_wfd(const WOLFSSL* ssl)
1313
0
{
1314
0
    int fd = -1;
1315
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1316
0
    if (ssl) {
1317
0
        fd = ssl->wfd;
1318
0
    }
1319
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1320
0
    return fd;
1321
0
}
1322
1323
1324
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
1325
1326
int wolfSSL_CTX_set_AcceptFilter(
1327
    WOLFSSL_CTX *ctx,
1328
    NetworkFilterCallback_t AcceptFilter,
1329
    void *AcceptFilter_arg)
1330
{
1331
    if (ctx == NULL)
1332
        return BAD_FUNC_ARG;
1333
    ctx->AcceptFilter = AcceptFilter;
1334
    ctx->AcceptFilter_arg = AcceptFilter_arg;
1335
    return 0;
1336
}
1337
1338
int wolfSSL_set_AcceptFilter(
1339
    WOLFSSL *ssl,
1340
    NetworkFilterCallback_t AcceptFilter,
1341
    void *AcceptFilter_arg)
1342
{
1343
    if (ssl == NULL)
1344
        return BAD_FUNC_ARG;
1345
    ssl->AcceptFilter = AcceptFilter;
1346
    ssl->AcceptFilter_arg = AcceptFilter_arg;
1347
    return 0;
1348
}
1349
1350
int wolfSSL_CTX_set_ConnectFilter(
1351
    WOLFSSL_CTX *ctx,
1352
    NetworkFilterCallback_t ConnectFilter,
1353
    void *ConnectFilter_arg)
1354
{
1355
    if (ctx == NULL)
1356
        return BAD_FUNC_ARG;
1357
    ctx->ConnectFilter = ConnectFilter;
1358
    ctx->ConnectFilter_arg = ConnectFilter_arg;
1359
    return 0;
1360
}
1361
1362
int wolfSSL_set_ConnectFilter(
1363
    WOLFSSL *ssl,
1364
    NetworkFilterCallback_t ConnectFilter,
1365
    void *ConnectFilter_arg)
1366
{
1367
    if (ssl == NULL)
1368
        return BAD_FUNC_ARG;
1369
    ssl->ConnectFilter = ConnectFilter;
1370
    ssl->ConnectFilter_arg = ConnectFilter_arg;
1371
    return 0;
1372
}
1373
1374
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
1375
1376
1377
#ifndef NO_TLS
1378
/* return underlying connect or accept, WOLFSSL_SUCCESS on ok */
1379
int wolfSSL_negotiate(WOLFSSL* ssl)
1380
0
{
1381
0
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
1382
1383
0
    WOLFSSL_ENTER("wolfSSL_negotiate");
1384
1385
0
    if (ssl == NULL)
1386
0
        return WOLFSSL_FATAL_ERROR;
1387
1388
0
#ifndef NO_WOLFSSL_SERVER
1389
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1390
0
#ifdef WOLFSSL_TLS13
1391
0
        if (IsAtLeastTLSv1_3(ssl->version))
1392
0
            err = wolfSSL_accept_TLSv13(ssl);
1393
0
        else
1394
0
#endif
1395
0
            err = wolfSSL_accept(ssl);
1396
0
    }
1397
0
#endif
1398
1399
0
#ifndef NO_WOLFSSL_CLIENT
1400
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1401
0
#ifdef WOLFSSL_TLS13
1402
0
        if (IsAtLeastTLSv1_3(ssl->version))
1403
0
            err = wolfSSL_connect_TLSv13(ssl);
1404
0
        else
1405
0
#endif
1406
0
            err = wolfSSL_connect(ssl);
1407
0
    }
1408
0
#endif
1409
1410
0
    (void)ssl;
1411
1412
0
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
1413
1414
0
    return err;
1415
0
}
1416
#endif /* !NO_TLS */
1417
1418
WOLFSSL_ABI
1419
WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
1420
0
{
1421
0
    if (ssl) {
1422
0
        return ssl->rng;
1423
0
    }
1424
1425
0
    return NULL;
1426
0
}
1427
1428
1429
#ifndef WOLFSSL_LEANPSK
1430
/* object size based on build */
1431
int wolfSSL_GetObjectSize(void)
1432
0
{
1433
#ifdef SHOW_SIZES
1434
    printf("sizeof suites           = %lu\n", (unsigned long)sizeof(Suites));
1435
    printf("sizeof ciphers(2)       = %lu\n", (unsigned long)sizeof(Ciphers));
1436
#ifndef NO_RC4
1437
    printf("\tsizeof arc4         = %lu\n", (unsigned long)sizeof(Arc4));
1438
#endif
1439
    printf("\tsizeof aes          = %lu\n", (unsigned long)sizeof(Aes));
1440
#ifndef NO_DES3
1441
    printf("\tsizeof des3         = %lu\n", (unsigned long)sizeof(Des3));
1442
#endif
1443
#ifdef HAVE_CHACHA
1444
    printf("\tsizeof chacha       = %lu\n", (unsigned long)sizeof(ChaCha));
1445
#endif
1446
#ifdef WOLFSSL_SM4
1447
    printf("\tsizeof sm4          = %lu\n", (unsigned long)sizeof(Sm4));
1448
#endif
1449
    printf("sizeof cipher specs     = %lu\n", (unsigned long)
1450
        sizeof(CipherSpecs));
1451
    printf("sizeof keys             = %lu\n", (unsigned long)sizeof(Keys));
1452
    printf("sizeof Hashes(2)        = %lu\n", (unsigned long)sizeof(Hashes));
1453
#ifndef NO_MD5
1454
    printf("\tsizeof MD5          = %lu\n", (unsigned long)sizeof(wc_Md5));
1455
#endif
1456
#ifndef NO_SHA
1457
    printf("\tsizeof SHA          = %lu\n", (unsigned long)sizeof(wc_Sha));
1458
#endif
1459
#ifdef WOLFSSL_SHA224
1460
    printf("\tsizeof SHA224       = %lu\n", (unsigned long)sizeof(wc_Sha224));
1461
#endif
1462
#ifndef NO_SHA256
1463
    printf("\tsizeof SHA256       = %lu\n", (unsigned long)sizeof(wc_Sha256));
1464
#endif
1465
#ifdef WOLFSSL_SHA384
1466
    printf("\tsizeof SHA384       = %lu\n", (unsigned long)sizeof(wc_Sha384));
1467
#endif
1468
#ifdef WOLFSSL_SHA384
1469
    printf("\tsizeof SHA512       = %lu\n", (unsigned long)sizeof(wc_Sha512));
1470
#endif
1471
#ifdef WOLFSSL_SM3
1472
    printf("\tsizeof sm3          = %lu\n", (unsigned long)sizeof(Sm3));
1473
#endif
1474
    printf("sizeof Buffers          = %lu\n", (unsigned long)sizeof(Buffers));
1475
    printf("sizeof Options          = %lu\n", (unsigned long)sizeof(Options));
1476
    printf("sizeof Arrays           = %lu\n", (unsigned long)sizeof(Arrays));
1477
#ifndef NO_RSA
1478
    printf("sizeof RsaKey           = %lu\n", (unsigned long)sizeof(RsaKey));
1479
#endif
1480
#ifdef HAVE_ECC
1481
    printf("sizeof ecc_key          = %lu\n", (unsigned long)sizeof(ecc_key));
1482
#endif
1483
    printf("sizeof WOLFSSL_CIPHER    = %lu\n", (unsigned long)
1484
        sizeof(WOLFSSL_CIPHER));
1485
    printf("sizeof WOLFSSL_SESSION   = %lu\n", (unsigned long)
1486
        sizeof(WOLFSSL_SESSION));
1487
    printf("sizeof WOLFSSL           = %lu\n", (unsigned long)sizeof(WOLFSSL));
1488
    printf("sizeof WOLFSSL_CTX       = %lu\n", (unsigned long)
1489
        sizeof(WOLFSSL_CTX));
1490
#endif
1491
1492
0
    return sizeof(WOLFSSL);
1493
0
}
1494
1495
int wolfSSL_CTX_GetObjectSize(void)
1496
0
{
1497
0
    return sizeof(WOLFSSL_CTX);
1498
0
}
1499
1500
int wolfSSL_METHOD_GetObjectSize(void)
1501
0
{
1502
0
    return sizeof(WOLFSSL_METHOD);
1503
0
}
1504
#endif
1505
1506
1507
#ifdef WOLFSSL_STATIC_MEMORY
1508
1509
int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx,
1510
    wolfSSL_method_func method, unsigned char* buf, unsigned int sz, int flag,
1511
    int maxSz)
1512
{
1513
    WOLFSSL_HEAP_HINT* hint = NULL;
1514
1515
    if (ctx == NULL || buf == NULL) {
1516
        return BAD_FUNC_ARG;
1517
    }
1518
1519
    if (*ctx == NULL && method == NULL) {
1520
        return BAD_FUNC_ARG;
1521
    }
1522
1523
    /* If there is a heap already, capture it in hint. */
1524
    if (*ctx && (*ctx)->heap != NULL) {
1525
        hint = (*ctx)->heap;
1526
    }
1527
1528
    if (wc_LoadStaticMemory(&hint, buf, sz, flag, maxSz)) {
1529
        WOLFSSL_MSG("Error loading static memory");
1530
        return WOLFSSL_FAILURE;
1531
    }
1532
1533
    if (*ctx) {
1534
        if ((*ctx)->heap == NULL) {
1535
            (*ctx)->heap = (void*)hint;
1536
        }
1537
    }
1538
    else {
1539
        /* create ctx if needed */
1540
        *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
1541
        if (*ctx == NULL) {
1542
            WOLFSSL_MSG("Error creating ctx");
1543
            return WOLFSSL_FAILURE;
1544
        }
1545
    }
1546
1547
    return WOLFSSL_SUCCESS;
1548
}
1549
1550
1551
int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
1552
{
1553
    if (ssl == NULL) {
1554
        return BAD_FUNC_ARG;
1555
    }
1556
    WOLFSSL_ENTER("wolfSSL_is_static_memory");
1557
1558
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
1559
    /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
1560
    if (mem_stats != NULL && ssl->heap != NULL) {
1561
        WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
1562
        WOLFSSL_HEAP* heap      = hint->memory;
1563
        if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
1564
            XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
1565
        }
1566
    }
1567
#endif
1568
1569
    (void)mem_stats;
1570
    return (ssl->heap) ? 1 : 0;
1571
}
1572
1573
1574
int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
1575
{
1576
    if (ctx == NULL) {
1577
        return BAD_FUNC_ARG;
1578
    }
1579
    WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
1580
1581
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
1582
    /* fill out statistics if wanted */
1583
    if (mem_stats != NULL && ctx->heap != NULL) {
1584
        WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
1585
        if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
1586
            return MEMORY_E;
1587
        }
1588
    }
1589
#endif
1590
1591
    (void)mem_stats;
1592
    return (ctx->heap) ? 1 : 0;
1593
}
1594
1595
#endif /* WOLFSSL_STATIC_MEMORY */
1596
1597
#ifndef NO_TLS
1598
/* return max record layer size plaintext input size */
1599
int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
1600
0
{
1601
0
    WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
1602
1603
0
    if (ssl == NULL)
1604
0
        return BAD_FUNC_ARG;
1605
1606
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE) {
1607
0
        WOLFSSL_MSG("Handshake not complete yet");
1608
0
        return BAD_FUNC_ARG;
1609
0
    }
1610
1611
0
    return min(OUTPUT_RECORD_SIZE, wolfssl_local_GetMaxPlaintextSize(ssl));
1612
0
}
1613
1614
1615
/* return record layer size of plaintext input size */
1616
int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
1617
0
{
1618
0
    int maxSize;
1619
1620
0
    WOLFSSL_ENTER("wolfSSL_GetOutputSize");
1621
1622
0
    if (inSz < 0)
1623
0
        return BAD_FUNC_ARG;
1624
1625
0
    maxSize = wolfSSL_GetMaxOutputSize(ssl);
1626
0
    if (maxSize < 0)
1627
0
        return maxSize;   /* error */
1628
0
    if (inSz > maxSize)
1629
0
        return INPUT_SIZE_E;
1630
1631
0
    return wolfssl_local_GetRecordSize(ssl, inSz, 1);
1632
0
}
1633
1634
1635
static int wolfSSL_write_internal(WOLFSSL* ssl, const void* data, size_t sz)
1636
0
{
1637
0
    int ret = 0;
1638
1639
0
    WOLFSSL_ENTER("wolfSSL_write");
1640
1641
0
    if (ssl == NULL || data == NULL)
1642
0
        return BAD_FUNC_ARG;
1643
1644
#ifdef WOLFSSL_QUIC
1645
    if (WOLFSSL_IS_QUIC(ssl)) {
1646
        WOLFSSL_MSG("SSL_write() on QUIC not allowed");
1647
        return BAD_FUNC_ARG;
1648
    }
1649
#endif
1650
1651
#ifdef HAVE_WRITE_DUP
1652
    if (ssl->dupSide == READ_DUP_SIDE) {
1653
        WOLFSSL_MSG("Read dup side cannot write");
1654
        return WRITE_DUP_WRITE_E;
1655
    }
1656
    /* Only enter special dupWrite logic when error is cleared. This will help
1657
     * with handling async data and other edge case errors. */
1658
    if (ssl->dupWrite != NULL && ssl->error == 0) {
1659
        int dupErr = 0;   /* local copy */
1660
        /* Lock ssl->dupWrite to gather what needs to be done. */
1661
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
1662
            return BAD_MUTEX_E;
1663
        dupErr = ssl->dupWrite->dupErr;
1664
#ifdef WOLFSSL_TLS13
1665
        if (IsAtLeastTLSv1_3(ssl->version)) {
1666
            /* TLS 1.3: if the read side received a KeyUpdate(update_requested)
1667
             * it cannot respond; send the response from here. */
1668
            ssl->keys.keyUpdateRespond |= ssl->dupWrite->keyUpdateRespond;
1669
            ssl->dupWrite->keyUpdateRespond = 0;
1670
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
1671
            ssl->postHandshakeAuthPending |=
1672
                    ssl->dupWrite->postHandshakeAuthPending;
1673
            ssl->dupWrite->postHandshakeAuthPending = 0;
1674
            if (ssl->postHandshakeAuthPending) {
1675
                /* Take ownership of the delegated auth state. */
1676
                CertReqCtx** tail = &ssl->dupWrite->postHandshakeCertReqCtx;
1677
                while (*tail != NULL)
1678
                    tail = &(*tail)->next;
1679
                *tail = ssl->certReqCtx;
1680
                ssl->certReqCtx = ssl->dupWrite->postHandshakeCertReqCtx;
1681
                ssl->dupWrite->postHandshakeCertReqCtx = NULL;
1682
                FreeHandshakeHashes(ssl);
1683
                ssl->hsHashes = ssl->dupWrite->postHandshakeHashState;
1684
                ssl->dupWrite->postHandshakeHashState = NULL;
1685
                ssl->options.sendVerify = ssl->dupWrite->postHandshakeSendVerify;
1686
                ssl->options.sigAlgo = ssl->dupWrite->postHandshakeSigAlgo;
1687
                ssl->options.hashAlgo = ssl->dupWrite->postHandshakeHashAlgo;
1688
            }
1689
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
1690
#ifdef WOLFSSL_DTLS13
1691
            if (ssl->options.dtls) {
1692
                /* Schedule key update to be sent. */
1693
                if (ssl->keys.keyUpdateRespond)
1694
                    ssl->dtls13DoKeyUpdate = 1;
1695
1696
                /* Copy over ACKs */
1697
                ssl->dtls13Rtx.sendAcks |= ssl->dupWrite->sendAcks;
1698
                if (ssl->dupWrite->sendAcks) {
1699
                    /* Insert each record number so the
1700
                     * ACK message is properly ordered. */
1701
                    struct Dtls13RecordNumber* rn;
1702
                    for (rn = ssl->dupWrite->sendAckList; rn != NULL;
1703
                         rn = rn->next) {
1704
                        ret = Dtls13RtxAddAck(ssl, rn->epoch, rn->seq);
1705
                        if (ret != 0)
1706
                            break;
1707
                    }
1708
                    /* Clear only on success so no ACKs get dropped */
1709
                    if (ret == 0) {
1710
                        rn = ssl->dupWrite->sendAckList;
1711
                        ssl->dupWrite->sendAckList = NULL;
1712
                        ssl->dupWrite->sendAcks = 0;
1713
                        while (rn != NULL) {
1714
                            struct Dtls13RecordNumber* next = rn->next;
1715
                            XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
1716
                            rn = next;
1717
                        }
1718
                    }
1719
                }
1720
1721
                /* Remove KeyUpdate record from RTX list. */
1722
                if (ssl->dupWrite->keyUpdateAcked) {
1723
                    Dtls13RtxRemoveRecord(ssl, ssl->dupWrite->keyUpdateEpoch,
1724
                            ssl->dupWrite->keyUpdateSeq);
1725
                }
1726
                /* Store if KeyUpdate was ACKed. */
1727
                ssl->dtls13KeyUpdateAcked |= ssl->dupWrite->keyUpdateAcked;
1728
                ssl->dupWrite->keyUpdateAcked = 0;
1729
            }
1730
#endif /* WOLFSSL_DTLS13 */
1731
        }
1732
#endif /* WOLFSSL_TLS13 */
1733
        wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1734
1735
        if (dupErr != 0) {
1736
            WOLFSSL_MSG("Write dup error from other side");
1737
            ssl->error = dupErr;
1738
            return WOLFSSL_FATAL_ERROR;
1739
        }
1740
        if (ret != 0) {
1741
            ssl->error = ret;
1742
            return WOLFSSL_FATAL_ERROR;
1743
        }
1744
1745
1746
#ifdef WOLFSSL_TLS13
1747
        if (IsAtLeastTLSv1_3(ssl->version)) {
1748
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
1749
            /* Read side received a CertificateRequest but couldn't write;
1750
             * send Certificate+CertificateVerify+Finished from the write side. */
1751
            if (ssl->postHandshakeAuthPending) {
1752
                /* reset handshake states */
1753
                ssl->postHandshakeAuthPending = 0;
1754
                ssl->options.clientState = CLIENT_HELLO_COMPLETE;
1755
                ssl->options.connectState = FIRST_REPLY_DONE;
1756
                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
1757
                ssl->options.processReply = 0; /* doProcessInit */
1758
                if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
1759
                    if (ssl->error != WC_NO_ERR_TRACE(WANT_WRITE) &&
1760
                            ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) {
1761
                        WOLFSSL_MSG("Post-handshake auth send failed");
1762
                        ssl->error = POST_HAND_AUTH_ERROR;
1763
                    }
1764
                    return WOLFSSL_FATAL_ERROR;
1765
                }
1766
            }
1767
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
1768
#ifdef WOLFSSL_DTLS13
1769
            if (ssl->options.dtls) {
1770
                if (ssl->dtls13KeyUpdateAcked)
1771
                    ret = DoDtls13KeyUpdateAck(ssl);
1772
                ssl->dtls13KeyUpdateAcked = 0;
1773
                if (ret == 0)
1774
                    ret = Dtls13DoScheduledWork(ssl);
1775
            }
1776
            else
1777
#endif /* WOLFSSL_DTLS13 */
1778
            if (ssl->keys.keyUpdateRespond) /* cleared in SendTls13KeyUpdate */
1779
                ret = Tls13UpdateKeys(ssl);
1780
            if (ret != 0) {
1781
                ssl->error = ret;
1782
                return WOLFSSL_FATAL_ERROR;
1783
            }
1784
            /* WANT_WRITE is safe to clear. Data is buffered in output buffer
1785
             * or in DTLS RTX queue */
1786
            ret = 0;
1787
        }
1788
#endif /* WOLFSSL_TLS13 */
1789
    }
1790
#endif
1791
1792
0
#ifdef HAVE_ERRNO_H
1793
0
    errno = 0;
1794
0
#endif
1795
1796
    #ifdef OPENSSL_EXTRA
1797
    if (ssl->CBIS != NULL) {
1798
        ssl->CBIS(ssl, WOLFSSL_CB_WRITE, WOLFSSL_SUCCESS);
1799
        ssl->cbmode = WOLFSSL_CB_WRITE;
1800
    }
1801
    #endif
1802
0
    ret = SendData(ssl, data, sz);
1803
1804
0
    WOLFSSL_LEAVE("wolfSSL_write", ret);
1805
1806
0
    if (ret < 0)
1807
0
        return WOLFSSL_FATAL_ERROR;
1808
0
    else
1809
0
        return ret;
1810
0
}
1811
1812
WOLFSSL_ABI
1813
int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
1814
0
{
1815
0
    WOLFSSL_ENTER("wolfSSL_write");
1816
1817
0
    if (sz < 0)
1818
0
        return BAD_FUNC_ARG;
1819
1820
0
    return wolfSSL_write_internal(ssl, data, (size_t)sz);
1821
0
}
1822
1823
int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz)
1824
0
{
1825
0
    int maxLength;
1826
0
    int usedLength;
1827
1828
0
    WOLFSSL_ENTER("wolfSSL_inject");
1829
1830
0
    if (ssl == NULL || data == NULL || sz <= 0)
1831
0
        return BAD_FUNC_ARG;
1832
1833
0
    usedLength = (int)(ssl->buffers.inputBuffer.length -
1834
0
                       ssl->buffers.inputBuffer.idx);
1835
0
    maxLength  = (int)(ssl->buffers.inputBuffer.bufferSize -
1836
0
                       (word32)usedLength);
1837
1838
0
    if (sz > maxLength) {
1839
        /* Need to make space */
1840
0
        int ret;
1841
0
        if (ssl->buffers.clearOutputBuffer.length > 0) {
1842
            /* clearOutputBuffer points into so reallocating inputBuffer will
1843
             * invalidate clearOutputBuffer and lose app data */
1844
0
            WOLFSSL_MSG("Can't inject while there is application data to read");
1845
0
            return APP_DATA_READY;
1846
0
        }
1847
0
        ret = GrowInputBuffer(ssl, sz, usedLength);
1848
0
        if (ret < 0)
1849
0
            return ret;
1850
0
    }
1851
1852
0
    XMEMCPY(ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
1853
0
            data, sz);
1854
0
    ssl->buffers.inputBuffer.length += sz;
1855
1856
0
    return WOLFSSL_SUCCESS;
1857
0
}
1858
1859
1860
int wolfSSL_write_ex(WOLFSSL* ssl, const void* data, size_t sz, size_t* wr)
1861
0
{
1862
0
    int ret;
1863
1864
0
    if (wr != NULL) {
1865
0
        *wr = 0;
1866
0
    }
1867
1868
0
    ret = wolfSSL_write_internal(ssl, data, sz);
1869
0
    if (ret >= 0) {
1870
0
        if (wr != NULL) {
1871
0
            *wr = (size_t)ret;
1872
0
        }
1873
1874
        /* handle partial write cases, if not set then a partial write is
1875
         * considered a failure case, or if set and ret is 0 then is a fail */
1876
0
        if (ret == 0 && ssl->options.partialWrite) {
1877
0
            ret = 0;
1878
0
        }
1879
0
        else if ((size_t)ret < sz && !ssl->options.partialWrite) {
1880
0
            ret = 0;
1881
0
        }
1882
0
        else {
1883
            /* wrote out all application data, or wrote out 1 byte or more with
1884
             * partial write flag set */
1885
0
            ret = 1;
1886
0
        }
1887
0
    }
1888
0
    else {
1889
0
        ret = 0;
1890
0
    }
1891
1892
0
    return ret;
1893
0
}
1894
1895
1896
static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, size_t sz, int peek)
1897
0
{
1898
0
    int ret;
1899
1900
0
    WOLFSSL_ENTER("wolfSSL_read_internal");
1901
1902
0
    if (ssl == NULL || data == NULL)
1903
0
        return BAD_FUNC_ARG;
1904
1905
#ifdef WOLFSSL_QUIC
1906
    if (WOLFSSL_IS_QUIC(ssl)) {
1907
        WOLFSSL_MSG("SSL_read() on QUIC not allowed");
1908
        return BAD_FUNC_ARG;
1909
    }
1910
#endif
1911
#if defined(WOLFSSL_ERROR_CODE_OPENSSL) && defined(OPENSSL_EXTRA)
1912
    /* This additional logic is meant to simulate following openSSL behavior:
1913
     * After bidirectional SSL_shutdown complete, SSL_read returns 0 and
1914
     * SSL_get_error_code returns SSL_ERROR_ZERO_RETURN.
1915
     * This behavior is used to know the disconnect of the underlying
1916
     * transport layer.
1917
     *
1918
     * In this logic, CBIORecv is called with a read size of 0 to check the
1919
     * transport layer status. It also returns WOLFSSL_FAILURE so that
1920
     * SSL_read does not return a positive number on failure.
1921
     */
1922
1923
    /* make sure bidirectional TLS shutdown completes */
1924
    if (ssl->error == WOLFSSL_ERROR_SYSCALL || ssl->options.shutdownDone) {
1925
        /* ask the underlying transport the connection is closed */
1926
        if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx)
1927
            == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE))
1928
        {
1929
            ssl->options.isClosed = 1;
1930
            ssl->error = WOLFSSL_ERROR_ZERO_RETURN;
1931
        }
1932
        return WOLFSSL_FAILURE;
1933
    }
1934
#endif
1935
1936
#ifdef HAVE_WRITE_DUP
1937
    if (ssl->dupWrite && ssl->dupSide == WRITE_DUP_SIDE) {
1938
        WOLFSSL_MSG("Write dup side cannot read");
1939
        return WRITE_DUP_READ_E;
1940
    }
1941
#endif
1942
1943
0
#ifdef HAVE_ERRNO_H
1944
0
        errno = 0;
1945
0
#endif
1946
1947
0
    ret = ReceiveData(ssl, (byte*)data, sz, peek);
1948
1949
#ifdef HAVE_WRITE_DUP
1950
    if (ssl->dupWrite) {
1951
        if (ssl->error != 0 && ssl->error != WC_NO_ERR_TRACE(WANT_READ)
1952
        #ifdef WOLFSSL_ASYNC_CRYPT
1953
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
1954
        #endif
1955
        ) {
1956
            int notifyErr;
1957
1958
            WOLFSSL_MSG("Notifying write side of fatal read error");
1959
            notifyErr  = NotifyWriteSide(ssl, ssl->error);
1960
            if (notifyErr < 0) {
1961
                ret = ssl->error = notifyErr;
1962
            }
1963
        }
1964
    }
1965
#endif
1966
1967
0
    WOLFSSL_LEAVE("wolfSSL_read_internal", ret);
1968
1969
0
    if (ret < 0)
1970
0
        return WOLFSSL_FATAL_ERROR;
1971
0
    else
1972
0
        return ret;
1973
0
}
1974
1975
1976
int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz)
1977
0
{
1978
0
    WOLFSSL_ENTER("wolfSSL_peek");
1979
1980
0
    if (sz < 0)
1981
0
        return BAD_FUNC_ARG;
1982
1983
0
    return wolfSSL_read_internal(ssl, data, (size_t)sz, TRUE);
1984
0
}
1985
1986
1987
WOLFSSL_ABI
1988
int wolfSSL_read(WOLFSSL* ssl, void* data, int sz)
1989
0
{
1990
0
    WOLFSSL_ENTER("wolfSSL_read");
1991
1992
0
    if (sz < 0)
1993
0
        return BAD_FUNC_ARG;
1994
1995
    #ifdef OPENSSL_EXTRA
1996
    if (ssl == NULL) {
1997
        return BAD_FUNC_ARG;
1998
    }
1999
    if (ssl->CBIS != NULL) {
2000
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
2001
        ssl->cbmode = WOLFSSL_CB_READ;
2002
    }
2003
    #endif
2004
0
    return wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
2005
0
}
2006
2007
2008
/* returns 0 on failure and 1 on read */
2009
int wolfSSL_read_ex(WOLFSSL* ssl, void* data, size_t sz, size_t* rd)
2010
0
{
2011
0
    int ret;
2012
2013
    #ifdef OPENSSL_EXTRA
2014
    if (ssl == NULL) {
2015
        return BAD_FUNC_ARG;
2016
    }
2017
    if (ssl->CBIS != NULL) {
2018
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
2019
        ssl->cbmode = WOLFSSL_CB_READ;
2020
    }
2021
    #endif
2022
0
    ret = wolfSSL_read_internal(ssl, data, sz, FALSE);
2023
2024
0
    if (ret > 0 && rd != NULL) {
2025
0
        *rd = (size_t)ret;
2026
0
    }
2027
2028
0
    return ret > 0 ? 1 : 0;
2029
0
}
2030
2031
#endif /* !NO_TLS */
2032
2033
#define WOLFSSL_SSL_API_DTLS_INCLUDED
2034
#include "src/ssl_api_dtls.c"
2035
2036
/* helpers to set the device id, WOLFSSL_SUCCESS on ok */
2037
WOLFSSL_ABI
2038
int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
2039
0
{
2040
0
    if (ssl == NULL)
2041
0
        return BAD_FUNC_ARG;
2042
2043
0
    ssl->devId = devId;
2044
2045
0
    return WOLFSSL_SUCCESS;
2046
0
}
2047
2048
WOLFSSL_ABI
2049
int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
2050
0
{
2051
0
    if (ctx == NULL)
2052
0
        return BAD_FUNC_ARG;
2053
2054
0
    ctx->devId = devId;
2055
2056
0
    return WOLFSSL_SUCCESS;
2057
0
}
2058
2059
/* helpers to get device id and heap */
2060
WOLFSSL_ABI
2061
int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
2062
0
{
2063
0
    int devId = INVALID_DEVID;
2064
0
    if (ssl != NULL)
2065
0
        devId = ssl->devId;
2066
0
    if (ctx != NULL && devId == INVALID_DEVID)
2067
0
        devId = ctx->devId;
2068
0
    return devId;
2069
0
}
2070
void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
2071
0
{
2072
0
    void* heap = NULL;
2073
0
    if (ctx != NULL)
2074
0
        heap = ctx->heap;
2075
0
    else if (ssl != NULL)
2076
0
        heap = ssl->heap;
2077
0
    return heap;
2078
0
}
2079
2080
2081
#ifndef NO_TLS
2082
2083
2084
#ifndef WOLFSSL_LEANPSK
2085
2086
int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags)
2087
0
{
2088
0
    int ret;
2089
0
    int oldFlags;
2090
2091
0
    WOLFSSL_ENTER("wolfSSL_send");
2092
2093
0
    if (ssl == NULL || data == NULL || sz < 0)
2094
0
        return BAD_FUNC_ARG;
2095
2096
0
    oldFlags = ssl->wflags;
2097
2098
0
    ssl->wflags = flags;
2099
0
    ret = wolfSSL_write(ssl, data, sz);
2100
0
    ssl->wflags = oldFlags;
2101
2102
0
    WOLFSSL_LEAVE("wolfSSL_send", ret);
2103
2104
0
    return ret;
2105
0
}
2106
2107
2108
int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags)
2109
0
{
2110
0
    int ret;
2111
0
    int oldFlags;
2112
2113
0
    WOLFSSL_ENTER("wolfSSL_recv");
2114
2115
0
    if (ssl == NULL || data == NULL || sz < 0)
2116
0
        return BAD_FUNC_ARG;
2117
2118
0
    oldFlags = ssl->rflags;
2119
2120
0
    ssl->rflags = flags;
2121
0
    ret = wolfSSL_read(ssl, data, sz);
2122
0
    ssl->rflags = oldFlags;
2123
2124
0
    WOLFSSL_LEAVE("wolfSSL_recv", ret);
2125
2126
0
    return ret;
2127
0
}
2128
#endif
2129
2130
int wolfSSL_SendUserCanceled(WOLFSSL* ssl)
2131
0
{
2132
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
2133
0
    WOLFSSL_ENTER("wolfSSL_recv");
2134
2135
0
    if (ssl != NULL) {
2136
0
        ssl->error = SendAlert(ssl, alert_warning, user_canceled);
2137
0
        if (ssl->error < 0) {
2138
0
            WOLFSSL_ERROR(ssl->error);
2139
0
        }
2140
0
        else {
2141
0
            ret = wolfSSL_shutdown(ssl);
2142
0
        }
2143
0
    }
2144
2145
0
    WOLFSSL_LEAVE("wolfSSL_SendUserCanceled", ret);
2146
2147
0
    return ret;
2148
0
}
2149
2150
/* WOLFSSL_SUCCESS on ok */
2151
WOLFSSL_ABI
2152
int wolfSSL_shutdown(WOLFSSL* ssl)
2153
0
{
2154
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
2155
0
    WOLFSSL_ENTER("wolfSSL_shutdown");
2156
2157
0
    if (ssl == NULL)
2158
0
        return WOLFSSL_FATAL_ERROR;
2159
2160
0
    if (ssl->options.quietShutdown) {
2161
0
        WOLFSSL_MSG("quiet shutdown, no close notify sent");
2162
0
        ret = WOLFSSL_SUCCESS;
2163
0
    }
2164
0
    else {
2165
2166
        /* Try to flush the buffer first, it might contain the alert */
2167
0
        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE) &&
2168
0
            ssl->buffers.outputBuffer.length > 0) {
2169
0
            ret = SendBuffered(ssl);
2170
0
            if (ret != 0) {
2171
0
                ssl->error = ret;
2172
                /* for error tracing */
2173
0
                if (ret != WC_NO_ERR_TRACE(WANT_WRITE))
2174
0
                    WOLFSSL_ERROR(ret);
2175
0
                ret = WOLFSSL_FATAL_ERROR;
2176
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
2177
0
                return ret;
2178
0
            }
2179
2180
0
            ssl->error = WOLFSSL_ERROR_NONE;
2181
            /* we succeeded in sending the alert now */
2182
0
            if (ssl->options.sentNotify)  {
2183
                /* just after we send the alert, if we didn't receive the alert
2184
                 * from the other peer yet, return WOLFSSL_STHUDOWN_NOT_DONE */
2185
0
                if (!ssl->options.closeNotify) {
2186
0
                    ret = WOLFSSL_SHUTDOWN_NOT_DONE;
2187
0
                    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
2188
0
                    return ret;
2189
0
                }
2190
0
                else {
2191
0
                    ssl->options.shutdownDone = 1;
2192
0
                    ret = WOLFSSL_SUCCESS;
2193
0
                }
2194
0
            }
2195
0
        }
2196
2197
        /* try to send close notify, not an error if can't */
2198
0
        if (!ssl->options.isClosed && !ssl->options.connReset &&
2199
0
                                      !ssl->options.sentNotify) {
2200
0
            ssl->error = SendAlert(ssl, alert_warning, close_notify);
2201
2202
            /* the alert is now sent or sitting in the buffer,
2203
             * where will be sent eventually */
2204
0
            if (ssl->error == 0 || ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
2205
0
                ssl->options.sentNotify = 1;
2206
2207
0
            if (ssl->error < 0) {
2208
0
                WOLFSSL_ERROR(ssl->error);
2209
0
                return WOLFSSL_FATAL_ERROR;
2210
0
            }
2211
2212
0
            if (ssl->options.closeNotify) {
2213
0
                ret = WOLFSSL_SUCCESS;
2214
0
                ssl->options.shutdownDone = 1;
2215
0
            }
2216
0
            else {
2217
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
2218
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
2219
0
                return ret;
2220
0
            }
2221
0
        }
2222
2223
#ifdef WOLFSSL_SHUTDOWNONCE
2224
        if (ssl->options.isClosed || ssl->options.connReset) {
2225
            /* Shutdown has already occurred.
2226
             * Caller is free to ignore this error. */
2227
            return SSL_SHUTDOWN_ALREADY_DONE_E;
2228
        }
2229
#endif
2230
2231
        /* wolfSSL_shutdown called again for bidirectional shutdown */
2232
0
        if (ssl->options.sentNotify && !ssl->options.closeNotify) {
2233
            /* If there is still buffered application data waiting to be read,
2234
             * do not process incoming records here. clearOutputBuffer.buffer
2235
             * points into inputBuffer, and ProcessReply() may call
2236
             * GrowInputBuffer(), which frees and reallocates inputBuffer.
2237
             * Require the pending data to be drained first. */
2238
0
            if (ssl->buffers.clearOutputBuffer.length > 0) {
2239
0
                WOLFSSL_MSG("Pending application data, read it before shutdown");
2240
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
2241
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
2242
0
                return ret;
2243
0
            }
2244
0
            ret = ProcessReply(ssl);
2245
0
            if ((ret == WC_NO_ERR_TRACE(ZERO_RETURN)) ||
2246
0
                (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))) {
2247
                /* simulate OpenSSL behavior */
2248
0
                ssl->options.shutdownDone = 1;
2249
                /* Clear error */
2250
0
                ssl->error = WOLFSSL_ERROR_NONE;
2251
0
                ret = WOLFSSL_SUCCESS;
2252
0
            }
2253
0
            else if (ret == WC_NO_ERR_TRACE(MEMORY_E)) {
2254
0
                ret = WOLFSSL_FATAL_ERROR;
2255
0
            }
2256
0
            else if (ret == WC_NO_ERR_TRACE(WANT_READ)) {
2257
0
                ssl->error = ret;
2258
0
                ret = WOLFSSL_FATAL_ERROR;
2259
0
            }
2260
0
            else if (ssl->error == WOLFSSL_ERROR_NONE) {
2261
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
2262
0
            }
2263
0
            else {
2264
0
                WOLFSSL_ERROR(ssl->error);
2265
0
                ret = WOLFSSL_FATAL_ERROR;
2266
0
            }
2267
0
        }
2268
0
    }
2269
2270
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
2271
    /* reset WOLFSSL structure state for possible reuse */
2272
    if (ret == WOLFSSL_SUCCESS) {
2273
        if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) {
2274
            WOLFSSL_MSG("could not clear WOLFSSL");
2275
            ret = WOLFSSL_FATAL_ERROR;
2276
        }
2277
    }
2278
#endif
2279
2280
0
    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
2281
2282
0
    return ret;
2283
0
}
2284
#endif /* !NO_TLS */
2285
2286
/* get current error state value */
2287
int wolfSSL_state(WOLFSSL* ssl)
2288
0
{
2289
0
    if (ssl == NULL) {
2290
0
        return BAD_FUNC_ARG;
2291
0
    }
2292
2293
0
    return ssl->error;
2294
0
}
2295
2296
2297
WOLFSSL_ABI
2298
int wolfSSL_get_error(WOLFSSL* ssl, int ret)
2299
0
{
2300
0
    WOLFSSL_ENTER("wolfSSL_get_error");
2301
2302
0
    if (ret > 0)
2303
0
        return WOLFSSL_ERROR_NONE;
2304
0
    if (ssl == NULL)
2305
0
        return BAD_FUNC_ARG;
2306
2307
0
    WOLFSSL_LEAVE("wolfSSL_get_error", ssl->error);
2308
2309
    /* make sure converted types are handled in SetErrorString() too */
2310
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
2311
0
        return WOLFSSL_ERROR_WANT_READ;         /* convert to OpenSSL type */
2312
0
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
2313
0
        return WOLFSSL_ERROR_WANT_WRITE;        /* convert to OpenSSL type */
2314
0
    else if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) ||
2315
0
             ssl->options.shutdownDone)
2316
0
        return WOLFSSL_ERROR_ZERO_RETURN;       /* convert to OpenSSL type */
2317
#ifdef OPENSSL_EXTRA
2318
    else if (ssl->error == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
2319
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
2320
    else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E))
2321
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
2322
#endif
2323
#ifdef WOLFSSL_ASYNC_CRYPT
2324
    else if (ssl->error == WC_NO_ERR_TRACE(MP_WOULDBLOCK))
2325
        return WC_PENDING_E;                    /* map non-blocking crypto */
2326
#endif
2327
0
    return ssl->error;
2328
0
}
2329
2330
2331
/* retrieve alert history, WOLFSSL_SUCCESS on ok */
2332
int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
2333
0
{
2334
0
    if (ssl && h) {
2335
0
        *h = ssl->alert_history;
2336
0
    }
2337
0
    return WOLFSSL_SUCCESS;
2338
0
}
2339
2340
#ifdef OPENSSL_EXTRA
2341
/* returns SSL_WRITING, SSL_READING or SSL_NOTHING */
2342
int wolfSSL_want(WOLFSSL* ssl)
2343
{
2344
    int rw_state = WOLFSSL_NOTHING;
2345
    if (ssl) {
2346
        if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
2347
            rw_state = WOLFSSL_READING;
2348
        else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
2349
            rw_state = WOLFSSL_WRITING;
2350
    }
2351
    return rw_state;
2352
}
2353
#endif
2354
2355
/* return TRUE if current error is want read */
2356
int wolfSSL_want_read(WOLFSSL* ssl)
2357
0
{
2358
0
    WOLFSSL_ENTER("wolfSSL_want_read");
2359
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
2360
0
        return 1;
2361
2362
0
    return 0;
2363
0
}
2364
2365
/* return TRUE if current error is want write */
2366
int wolfSSL_want_write(WOLFSSL* ssl)
2367
0
{
2368
0
    WOLFSSL_ENTER("wolfSSL_want_write");
2369
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
2370
0
        return 1;
2371
2372
0
    return 0;
2373
0
}
2374
2375
char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data)
2376
0
{
2377
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string");
2378
0
    if (data) {
2379
0
        SetErrorString((int)errNumber, data);
2380
0
        return data;
2381
0
    }
2382
0
    else {
2383
0
        static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0};
2384
0
        SetErrorString((int)errNumber, tmp);
2385
0
        return tmp;
2386
0
    }
2387
0
}
2388
2389
2390
void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
2391
0
{
2392
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string_n");
2393
0
    if (len >= WOLFSSL_MAX_ERROR_SZ)
2394
0
        wolfSSL_ERR_error_string(e, buf);
2395
0
    else {
2396
0
        WOLFSSL_MSG("Error buffer too short, truncating");
2397
0
        if (len) {
2398
0
            char tmp[WOLFSSL_MAX_ERROR_SZ];
2399
0
            wolfSSL_ERR_error_string(e, tmp);
2400
0
            XMEMCPY(buf, tmp, len-1);
2401
0
            buf[len-1] = '\0';
2402
0
        }
2403
0
    }
2404
0
}
2405
2406
2407
/* don't free temporary arrays at end of handshake */
2408
void wolfSSL_KeepArrays(WOLFSSL* ssl)
2409
0
{
2410
0
    if (ssl)
2411
0
        ssl->options.saveArrays = 1;
2412
0
}
2413
2414
2415
/* user doesn't need temporary arrays anymore, Free */
2416
void wolfSSL_FreeArrays(WOLFSSL* ssl)
2417
0
{
2418
0
    if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
2419
0
        ssl->options.saveArrays = 0;
2420
0
        FreeArrays(ssl, 1);
2421
0
    }
2422
0
}
2423
2424
/* Set option to indicate that the resources are not to be freed after
2425
 * handshake.
2426
 *
2427
 * ssl  The SSL/TLS object.
2428
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
2429
 */
2430
int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
2431
0
{
2432
0
    if (ssl == NULL)
2433
0
        return BAD_FUNC_ARG;
2434
2435
0
    ssl->options.keepResources = 1;
2436
2437
0
    return 0;
2438
0
}
2439
2440
/* Free the handshake resources after handshake.
2441
 *
2442
 * ssl  The SSL/TLS object.
2443
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
2444
 */
2445
int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
2446
0
{
2447
0
    if (ssl == NULL)
2448
0
        return BAD_FUNC_ARG;
2449
2450
0
    FreeHandshakeResources(ssl);
2451
2452
0
    return 0;
2453
0
}
2454
2455
/* Use the client's order of preference when matching cipher suites.
2456
 *
2457
 * ssl  The SSL/TLS context object.
2458
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
2459
 */
2460
int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
2461
0
{
2462
0
    if (ctx == NULL)
2463
0
        return BAD_FUNC_ARG;
2464
2465
0
    ctx->useClientOrder = 1;
2466
2467
0
    return 0;
2468
0
}
2469
2470
/* Use the client's order of preference when matching cipher suites.
2471
 *
2472
 * ssl  The SSL/TLS object.
2473
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
2474
 */
2475
int wolfSSL_UseClientSuites(WOLFSSL* ssl)
2476
0
{
2477
0
    if (ssl == NULL)
2478
0
        return BAD_FUNC_ARG;
2479
2480
0
    ssl->options.useClientOrder = 1;
2481
2482
0
    return 0;
2483
0
}
2484
2485
2486
const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
2487
0
{
2488
0
#ifndef WOLFSSL_AEAD_ONLY
2489
0
    if (ssl == NULL)
2490
0
        return NULL;
2491
2492
0
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
2493
0
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
2494
0
        return ssl->keys.client_write_MAC_secret;
2495
0
    else
2496
0
        return ssl->keys.server_write_MAC_secret;
2497
#else
2498
    (void)ssl;
2499
    (void)verify;
2500
2501
    return NULL;
2502
#endif
2503
0
}
2504
2505
int wolfSSL_GetSide(WOLFSSL* ssl)
2506
0
{
2507
0
    if (ssl)
2508
0
        return ssl->options.side;
2509
2510
0
    return BAD_FUNC_ARG;
2511
0
}
2512
2513
#ifdef ATOMIC_USER
2514
2515
void  wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
2516
{
2517
    if (ctx)
2518
        ctx->MacEncryptCb = cb;
2519
}
2520
2521
2522
void  wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
2523
{
2524
    if (ssl)
2525
        ssl->MacEncryptCtx = ctx;
2526
}
2527
2528
2529
void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
2530
{
2531
    if (ssl)
2532
        return ssl->MacEncryptCtx;
2533
2534
    return NULL;
2535
}
2536
2537
2538
void  wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
2539
{
2540
    if (ctx)
2541
        ctx->DecryptVerifyCb = cb;
2542
}
2543
2544
2545
void  wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
2546
{
2547
    if (ssl)
2548
        ssl->DecryptVerifyCtx = ctx;
2549
}
2550
2551
2552
void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
2553
{
2554
    if (ssl)
2555
        return ssl->DecryptVerifyCtx;
2556
2557
    return NULL;
2558
}
2559
2560
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
2561
/**
2562
 * Set the callback, against the context, that encrypts then MACs.
2563
 *
2564
 * ctx  SSL/TLS context.
2565
 * cb   Callback function to use with Encrypt-Then-MAC.
2566
 */
2567
void  wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
2568
{
2569
    if (ctx)
2570
        ctx->EncryptMacCb = cb;
2571
}
2572
2573
/**
2574
 * Set the context to use with callback that encrypts then MACs.
2575
 *
2576
 * ssl  SSL/TLS object.
2577
 * ctx  Callback function's context.
2578
 */
2579
void  wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
2580
{
2581
    if (ssl)
2582
        ssl->EncryptMacCtx = ctx;
2583
}
2584
2585
/**
2586
 * Get the context being used with callback that encrypts then MACs.
2587
 *
2588
 * ssl  SSL/TLS object.
2589
 * returns callback function's context or NULL if SSL/TLS object is NULL.
2590
 */
2591
void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
2592
{
2593
    if (ssl)
2594
        return ssl->EncryptMacCtx;
2595
2596
    return NULL;
2597
}
2598
2599
2600
/**
2601
 * Set the callback, against the context, that MAC verifies then decrypts.
2602
 *
2603
 * ctx  SSL/TLS context.
2604
 * cb   Callback function to use with Encrypt-Then-MAC.
2605
 */
2606
void  wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
2607
{
2608
    if (ctx)
2609
        ctx->VerifyDecryptCb = cb;
2610
}
2611
2612
/**
2613
 * Set the context to use with callback that MAC verifies then decrypts.
2614
 *
2615
 * ssl  SSL/TLS object.
2616
 * ctx  Callback function's context.
2617
 */
2618
void  wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
2619
{
2620
    if (ssl)
2621
        ssl->VerifyDecryptCtx = ctx;
2622
}
2623
2624
/**
2625
 * Get the context being used with callback that MAC verifies then decrypts.
2626
 *
2627
 * ssl  SSL/TLS object.
2628
 * returns callback function's context or NULL if SSL/TLS object is NULL.
2629
 */
2630
void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
2631
{
2632
    if (ssl)
2633
        return ssl->VerifyDecryptCtx;
2634
2635
    return NULL;
2636
}
2637
#endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
2638
2639
2640
2641
const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
2642
{
2643
    if (ssl)
2644
        return ssl->keys.client_write_key;
2645
2646
    return NULL;
2647
}
2648
2649
2650
const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
2651
{
2652
    if (ssl)
2653
        return ssl->keys.client_write_IV;
2654
2655
    return NULL;
2656
}
2657
2658
2659
const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
2660
{
2661
    if (ssl)
2662
        return ssl->keys.server_write_key;
2663
2664
    return NULL;
2665
}
2666
2667
2668
const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
2669
{
2670
    if (ssl)
2671
        return ssl->keys.server_write_IV;
2672
2673
    return NULL;
2674
}
2675
2676
int wolfSSL_GetKeySize(WOLFSSL* ssl)
2677
{
2678
    if (ssl)
2679
        return ssl->specs.key_size;
2680
2681
    return BAD_FUNC_ARG;
2682
}
2683
2684
2685
int wolfSSL_GetIVSize(WOLFSSL* ssl)
2686
{
2687
    if (ssl)
2688
        return ssl->specs.iv_size;
2689
2690
    return BAD_FUNC_ARG;
2691
}
2692
2693
2694
int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
2695
{
2696
    if (ssl)
2697
        return ssl->specs.bulk_cipher_algorithm;
2698
2699
    return BAD_FUNC_ARG;
2700
}
2701
2702
2703
int wolfSSL_GetCipherType(WOLFSSL* ssl)
2704
{
2705
    if (ssl == NULL)
2706
        return BAD_FUNC_ARG;
2707
2708
#ifndef WOLFSSL_AEAD_ONLY
2709
    if (ssl->specs.cipher_type == block)
2710
        return WOLFSSL_BLOCK_TYPE;
2711
    if (ssl->specs.cipher_type == stream)
2712
        return WOLFSSL_STREAM_TYPE;
2713
#endif
2714
    if (ssl->specs.cipher_type == aead)
2715
        return WOLFSSL_AEAD_TYPE;
2716
2717
    return WOLFSSL_FATAL_ERROR;
2718
}
2719
2720
2721
int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
2722
{
2723
    if (ssl == NULL)
2724
        return BAD_FUNC_ARG;
2725
2726
    return ssl->specs.block_size;
2727
}
2728
2729
2730
int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
2731
{
2732
    if (ssl == NULL)
2733
        return BAD_FUNC_ARG;
2734
2735
    return ssl->specs.aead_mac_size;
2736
}
2737
2738
2739
int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
2740
{
2741
    if (ssl == NULL)
2742
        return BAD_FUNC_ARG;
2743
2744
    if (ssl->options.tls1_1)
2745
        return 1;
2746
2747
    return 0;
2748
}
2749
2750
2751
2752
int wolfSSL_GetHmacSize(WOLFSSL* ssl)
2753
{
2754
    /* AEAD ciphers don't have HMAC keys */
2755
    if (ssl)
2756
        return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
2757
2758
    return BAD_FUNC_ARG;
2759
}
2760
2761
#ifdef WORD64_AVAILABLE
2762
int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
2763
{
2764
    if ((ssl == NULL) || (seq == NULL))
2765
        return BAD_FUNC_ARG;
2766
2767
    *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
2768
                    ssl->keys.peer_sequence_number_lo;
2769
    return !(*seq);
2770
}
2771
2772
int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
2773
{
2774
    if ((ssl == NULL) || (seq == NULL))
2775
        return BAD_FUNC_ARG;
2776
2777
    *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
2778
                    ssl->keys.sequence_number_lo;
2779
    return !(*seq);
2780
}
2781
#endif
2782
2783
#endif /* ATOMIC_USER */
2784
2785
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) \
2786
    && defined(XFPRINTF)
2787
2788
void wolfSSL_ERR_print_errors_fp(XFILE fp, int err)
2789
0
{
2790
0
    char data[WOLFSSL_MAX_ERROR_SZ + 1];
2791
2792
0
    WOLFSSL_ENTER("wolfSSL_ERR_print_errors_fp");
2793
0
    SetErrorString(err, data);
2794
0
    if (XFPRINTF(fp, "%s", data) < 0)
2795
0
        WOLFSSL_MSG("fprintf failed in wolfSSL_ERR_print_errors_fp");
2796
0
}
2797
2798
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
2799
void wolfSSL_ERR_dump_errors_fp(XFILE fp)
2800
{
2801
    wc_ERR_print_errors_fp(fp);
2802
}
2803
2804
void wolfSSL_ERR_print_errors_cb (int (*cb)(const char *str, size_t len,
2805
                                            void *u), void *u)
2806
{
2807
    wc_ERR_print_errors_cb(cb, u);
2808
}
2809
#endif
2810
#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM && XFPRINTF */
2811
2812
/*
2813
 * TODO This ssl parameter needs to be changed to const once our ABI checker
2814
 *      stops flagging qualifier additions as ABI breaking.
2815
 */
2816
WOLFSSL_ABI
2817
int wolfSSL_pending(WOLFSSL* ssl)
2818
0
{
2819
0
    WOLFSSL_ENTER("wolfSSL_pending");
2820
0
    if (ssl == NULL)
2821
0
        return WOLFSSL_FAILURE;
2822
2823
0
    return (int)ssl->buffers.clearOutputBuffer.length;
2824
0
}
2825
2826
int wolfSSL_has_pending(const WOLFSSL* ssl)
2827
0
{
2828
0
    WOLFSSL_ENTER("wolfSSL_has_pending");
2829
0
    if (ssl == NULL)
2830
0
        return WOLFSSL_FAILURE;
2831
2832
0
    return ssl->buffers.clearOutputBuffer.length > 0;
2833
0
}
2834
2835
#ifndef WOLFSSL_LEANPSK
2836
/* turn on handshake group messages for context */
2837
int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
2838
0
{
2839
0
    if (ctx == NULL)
2840
0
       return BAD_FUNC_ARG;
2841
2842
0
    ctx->groupMessages = 1;
2843
2844
0
    return WOLFSSL_SUCCESS;
2845
0
}
2846
2847
int wolfSSL_CTX_clear_group_messages(WOLFSSL_CTX* ctx)
2848
0
{
2849
0
    if (ctx == NULL)
2850
0
       return BAD_FUNC_ARG;
2851
2852
0
    ctx->groupMessages = 0;
2853
2854
0
    return WOLFSSL_SUCCESS;
2855
0
}
2856
#endif
2857
2858
2859
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
2860
/* connect enough to get peer cert chain */
2861
int wolfSSL_connect_cert(WOLFSSL* ssl)
2862
0
{
2863
0
    int  ret;
2864
2865
0
    if (ssl == NULL)
2866
0
        return WOLFSSL_FAILURE;
2867
2868
0
    ssl->options.certOnly = 1;
2869
0
    ret = wolfSSL_connect(ssl);
2870
0
    ssl->options.certOnly   = 0;
2871
2872
0
    return ret;
2873
0
}
2874
#endif
2875
2876
2877
#ifndef WOLFSSL_LEANPSK
2878
/* turn on handshake group messages for ssl object */
2879
int wolfSSL_set_group_messages(WOLFSSL* ssl)
2880
0
{
2881
0
    if (ssl == NULL)
2882
0
       return BAD_FUNC_ARG;
2883
2884
0
    ssl->options.groupMessages = 1;
2885
2886
0
    return WOLFSSL_SUCCESS;
2887
0
}
2888
2889
int wolfSSL_clear_group_messages(WOLFSSL* ssl)
2890
0
{
2891
0
    if (ssl == NULL)
2892
0
       return BAD_FUNC_ARG;
2893
2894
0
    ssl->options.groupMessages = 0;
2895
2896
0
    return WOLFSSL_SUCCESS;
2897
0
}
2898
2899
/* make minVersion the internal equivalent SSL version */
2900
static int SetMinVersionHelper(byte* minVersion, int version)
2901
0
{
2902
0
    (void)minVersion;
2903
2904
0
    switch (version) {
2905
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
2906
        case WOLFSSL_SSLV3:
2907
            *minVersion = SSLv3_MINOR;
2908
            break;
2909
#endif
2910
2911
0
#ifndef NO_TLS
2912
    #ifndef NO_OLD_TLS
2913
        #ifdef WOLFSSL_ALLOW_TLSV10
2914
        case WOLFSSL_TLSV1:
2915
            *minVersion = TLSv1_MINOR;
2916
            break;
2917
        #endif
2918
2919
        case WOLFSSL_TLSV1_1:
2920
            *minVersion = TLSv1_1_MINOR;
2921
            break;
2922
    #endif
2923
0
    #ifndef WOLFSSL_NO_TLS12
2924
0
        case WOLFSSL_TLSV1_2:
2925
0
            *minVersion = TLSv1_2_MINOR;
2926
0
            break;
2927
0
    #endif
2928
0
#endif
2929
0
    #ifdef WOLFSSL_TLS13
2930
0
        case WOLFSSL_TLSV1_3:
2931
0
            *minVersion = TLSv1_3_MINOR;
2932
0
            break;
2933
0
    #endif
2934
2935
#ifdef WOLFSSL_DTLS
2936
        case WOLFSSL_DTLSV1:
2937
            *minVersion = DTLS_MINOR;
2938
            break;
2939
        case WOLFSSL_DTLSV1_2:
2940
            *minVersion = DTLSv1_2_MINOR;
2941
            break;
2942
#ifdef WOLFSSL_DTLS13
2943
        case WOLFSSL_DTLSV1_3:
2944
            *minVersion = DTLSv1_3_MINOR;
2945
            break;
2946
#endif /* WOLFSSL_DTLS13 */
2947
#endif /* WOLFSSL_DTLS */
2948
2949
0
        default:
2950
0
            WOLFSSL_MSG("Bad function argument");
2951
0
            return BAD_FUNC_ARG;
2952
0
    }
2953
2954
0
    return WOLFSSL_SUCCESS;
2955
0
}
2956
2957
2958
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
2959
WOLFSSL_ABI
2960
int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
2961
0
{
2962
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
2963
2964
0
    if (ctx == NULL) {
2965
0
        WOLFSSL_MSG("Bad function argument");
2966
0
        return BAD_FUNC_ARG;
2967
0
    }
2968
2969
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2970
    if (crypto_policy.enabled) {
2971
        return CRYPTO_POLICY_FORBIDDEN;
2972
    }
2973
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2974
2975
0
    return SetMinVersionHelper(&ctx->minDowngrade, version);
2976
0
}
2977
2978
2979
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
2980
int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
2981
0
{
2982
0
    WOLFSSL_ENTER("wolfSSL_SetMinVersion");
2983
2984
0
    if (ssl == NULL) {
2985
0
        WOLFSSL_MSG("Bad function argument");
2986
0
        return BAD_FUNC_ARG;
2987
0
    }
2988
2989
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2990
    if (crypto_policy.enabled) {
2991
        return CRYPTO_POLICY_FORBIDDEN;
2992
    }
2993
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2994
2995
0
    return SetMinVersionHelper(&ssl->options.minDowngrade, version);
2996
0
}
2997
2998
2999
/* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
3000
int wolfSSL_GetVersion(const WOLFSSL* ssl)
3001
0
{
3002
0
    if (ssl == NULL)
3003
0
        return BAD_FUNC_ARG;
3004
3005
0
    if (ssl->version.major == SSLv3_MAJOR) {
3006
0
        switch (ssl->version.minor) {
3007
0
            case SSLv3_MINOR :
3008
0
                return WOLFSSL_SSLV3;
3009
0
            case TLSv1_MINOR :
3010
0
                return WOLFSSL_TLSV1;
3011
0
            case TLSv1_1_MINOR :
3012
0
                return WOLFSSL_TLSV1_1;
3013
0
            case TLSv1_2_MINOR :
3014
0
                return WOLFSSL_TLSV1_2;
3015
0
            case TLSv1_3_MINOR :
3016
0
                return WOLFSSL_TLSV1_3;
3017
0
            default:
3018
0
                break;
3019
0
        }
3020
0
    }
3021
#ifdef WOLFSSL_DTLS
3022
    if (ssl->version.major == DTLS_MAJOR) {
3023
        switch (ssl->version.minor) {
3024
            case DTLS_MINOR :
3025
                return WOLFSSL_DTLSV1;
3026
            case DTLSv1_2_MINOR :
3027
                return WOLFSSL_DTLSV1_2;
3028
            case DTLSv1_3_MINOR :
3029
                return WOLFSSL_DTLSV1_3;
3030
            default:
3031
                break;
3032
        }
3033
    }
3034
#endif /* WOLFSSL_DTLS */
3035
3036
0
    return VERSION_ERROR;
3037
0
}
3038
3039
int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
3040
0
{
3041
0
    word16 haveRSA = 1;
3042
0
    word16 havePSK = 0;
3043
0
    int    keySz   = 0;
3044
3045
0
    WOLFSSL_ENTER("wolfSSL_SetVersion");
3046
3047
0
    if (ssl == NULL) {
3048
0
        WOLFSSL_MSG("Bad function argument");
3049
0
        return BAD_FUNC_ARG;
3050
0
    }
3051
3052
0
    switch (version) {
3053
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
3054
        case WOLFSSL_SSLV3:
3055
            ssl->version = MakeSSLv3();
3056
            break;
3057
#endif
3058
3059
0
#ifndef NO_TLS
3060
    #ifndef NO_OLD_TLS
3061
        #ifdef WOLFSSL_ALLOW_TLSV10
3062
        case WOLFSSL_TLSV1:
3063
            ssl->version = MakeTLSv1();
3064
            break;
3065
        #endif
3066
3067
        case WOLFSSL_TLSV1_1:
3068
            ssl->version = MakeTLSv1_1();
3069
            break;
3070
    #endif
3071
0
    #ifndef WOLFSSL_NO_TLS12
3072
0
        case WOLFSSL_TLSV1_2:
3073
0
            ssl->version = MakeTLSv1_2();
3074
0
            break;
3075
0
    #endif
3076
3077
0
    #ifdef WOLFSSL_TLS13
3078
0
        case WOLFSSL_TLSV1_3:
3079
0
            ssl->version = MakeTLSv1_3();
3080
0
            break;
3081
0
    #endif /* WOLFSSL_TLS13 */
3082
0
#endif
3083
3084
0
        default:
3085
0
            WOLFSSL_MSG("Bad function argument");
3086
0
            return BAD_FUNC_ARG;
3087
0
    }
3088
3089
0
    ssl->options.downgrade = 0;
3090
3091
    #ifdef NO_RSA
3092
        haveRSA = 0;
3093
    #endif
3094
    #ifndef NO_PSK
3095
        havePSK = ssl->options.havePSK;
3096
    #endif
3097
0
    #ifndef NO_CERTS
3098
0
        keySz = ssl->buffers.keySz;
3099
0
    #endif
3100
3101
0
    if (AllocateSuites(ssl) != 0)
3102
0
        return WOLFSSL_FAILURE;
3103
0
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
3104
0
               ssl->options.haveDH, ssl->options.haveECDSAsig,
3105
0
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
3106
0
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
3107
0
    return WOLFSSL_SUCCESS;
3108
0
}
3109
#endif /* !leanpsk */
3110
3111
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
3112
static int wolfSSL_RAND_InitMutex(void);
3113
#endif
3114
3115
/* If we don't have static mutex initializers, but we do have static atomic
3116
 * initializers, activate WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS to leverage
3117
 * the latter.
3118
 *
3119
 * See further explanation below in wolfSSL_Init().
3120
 */
3121
#ifndef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3122
    #if !defined(WOLFSSL_MUTEX_INITIALIZER) && !defined(SINGLE_THREADED) && \
3123
            defined(WOLFSSL_ATOMIC_OPS) && defined(WOLFSSL_ATOMIC_INITIALIZER)
3124
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 1
3125
    #else
3126
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
3127
    #endif
3128
#elif defined(WOLFSSL_MUTEX_INITIALIZER) || defined(SINGLE_THREADED)
3129
    #undef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3130
    #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
3131
#endif
3132
3133
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3134
    #ifndef WOLFSSL_ATOMIC_OPS
3135
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_OPS
3136
    #endif
3137
    #ifndef WOLFSSL_ATOMIC_INITIALIZER
3138
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_INITIALIZER
3139
    #endif
3140
    static wolfSSL_Atomic_Int inits_count_mutex_atomic_initing_flag =
3141
        WOLFSSL_ATOMIC_INITIALIZER(0);
3142
#endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS && !WOLFSSL_MUTEX_INITIALIZER */
3143
3144
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
3145
static void AtExitCleanup(void)
3146
{
3147
    if (initRefCount > 0) {
3148
        initRefCount = 1;
3149
        (void)wolfSSL_Cleanup();
3150
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3151
        if (inits_count_mutex_valid == 1) {
3152
            (void)wc_FreeMutex(&inits_count_mutex);
3153
            inits_count_mutex_valid = 0;
3154
            inits_count_mutex_atomic_initing_flag = 0;
3155
        }
3156
#endif
3157
    }
3158
}
3159
#endif
3160
3161
WOLFSSL_ABI
3162
int wolfSSL_Init(void)
3163
0
{
3164
0
    int ret = WOLFSSL_SUCCESS;
3165
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
3166
    int i;
3167
#endif
3168
3169
0
    WOLFSSL_ENTER("wolfSSL_Init");
3170
3171
0
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
3172
0
    WOLFSSL_MSG(LIBWOLFSSL_CMAKE_OUTPUT);
3173
#else
3174
    WOLFSSL_MSG("No extra wolfSSL cmake messages found");
3175
#endif
3176
3177
#ifndef WOLFSSL_MUTEX_INITIALIZER
3178
    if (inits_count_mutex_valid == 0) {
3179
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3180
3181
        /* Without this mitigation, if two threads enter wolfSSL_Init() at the
3182
         * same time, and both see zero inits_count_mutex_valid, then both will
3183
         * run wc_InitMutex(&inits_count_mutex), leading to process corruption
3184
         * or (best case) a resource leak.
3185
         *
3186
         * When WOLFSSL_ATOMIC_INITIALIZER() is available, we can mitigate this
3187
         * by use an atomic counting int as a mutex.
3188
         */
3189
3190
        if (wolfSSL_Atomic_Int_FetchAdd(&inits_count_mutex_atomic_initing_flag,
3191
                                        1) != 0)
3192
        {
3193
            (void)wolfSSL_Atomic_Int_FetchSub(
3194
                &inits_count_mutex_atomic_initing_flag, 1);
3195
            return DEADLOCK_AVERTED_E;
3196
        }
3197
    #endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS */
3198
        if (wc_InitMutex(&inits_count_mutex) != 0) {
3199
            WOLFSSL_MSG("Bad Init Mutex count");
3200
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3201
            (void)wolfSSL_Atomic_Int_FetchSub(
3202
                &inits_count_mutex_atomic_initing_flag, 1);
3203
    #endif
3204
            return BAD_MUTEX_E;
3205
        }
3206
        else {
3207
            inits_count_mutex_valid = 1;
3208
        }
3209
    }
3210
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
3211
3212
0
    if (wc_LockMutex(&inits_count_mutex) != 0) {
3213
0
        WOLFSSL_MSG("Bad Lock Mutex count");
3214
0
        return BAD_MUTEX_E;
3215
0
    }
3216
3217
#if FIPS_VERSION_GE(5,1)
3218
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
3219
        ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL);
3220
        if (ret == 0)
3221
            ret = WOLFSSL_SUCCESS;
3222
    }
3223
#endif
3224
3225
0
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
3226
        /* Initialize crypto for use with TLS connection */
3227
3228
0
        if (wolfCrypt_Init() != 0) {
3229
0
            WOLFSSL_MSG("Bad wolfCrypt Init");
3230
0
            ret = WC_INIT_E;
3231
0
        }
3232
3233
#if defined(HAVE_GLOBAL_RNG) && !defined(WOLFSSL_MUTEX_INITIALIZER)
3234
        if (ret == WOLFSSL_SUCCESS) {
3235
            if (wc_InitMutex(&globalRNGMutex) != 0) {
3236
                WOLFSSL_MSG("Bad Init Mutex rng");
3237
                ret = BAD_MUTEX_E;
3238
            }
3239
            else {
3240
                globalRNGMutex_valid = 1;
3241
            }
3242
        }
3243
#endif
3244
3245
    #ifdef WC_RNG_SEED_CB
3246
        wc_SetSeed_Cb(WC_GENERATE_SEED_DEFAULT);
3247
    #endif
3248
3249
#ifdef OPENSSL_EXTRA
3250
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
3251
        if ((ret == WOLFSSL_SUCCESS) && (wolfSSL_RAND_InitMutex() != 0)) {
3252
            ret = BAD_MUTEX_E;
3253
        }
3254
    #endif
3255
        if ((ret == WOLFSSL_SUCCESS) &&
3256
            (wolfSSL_RAND_seed(NULL, 0) != WOLFSSL_SUCCESS)) {
3257
            WOLFSSL_MSG("wolfSSL_RAND_seed failed");
3258
            ret = WC_INIT_E;
3259
        }
3260
#endif
3261
3262
0
#ifndef NO_SESSION_CACHE
3263
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
3264
        for (i = 0; i < SESSION_ROWS; ++i) {
3265
            SessionCache[i].lock_valid = 0;
3266
        }
3267
        for (i = 0; (ret == WOLFSSL_SUCCESS) && (i < SESSION_ROWS); ++i) {
3268
            if (wc_InitRwLock(&SessionCache[i].row_lock) != 0) {
3269
                WOLFSSL_MSG("Bad Init Mutex session");
3270
                ret = BAD_MUTEX_E;
3271
            }
3272
            else {
3273
                SessionCache[i].lock_valid = 1;
3274
            }
3275
        }
3276
    #else
3277
0
        if (ret == WOLFSSL_SUCCESS) {
3278
0
            if (wc_InitRwLock(&session_lock) != 0) {
3279
0
                WOLFSSL_MSG("Bad Init Mutex session");
3280
0
                ret = BAD_MUTEX_E;
3281
0
            }
3282
0
            else {
3283
0
                session_lock_valid = 1;
3284
0
            }
3285
0
        }
3286
0
    #endif
3287
0
    #ifndef NO_CLIENT_CACHE
3288
        #ifndef WOLFSSL_MUTEX_INITIALIZER
3289
        if (ret == WOLFSSL_SUCCESS) {
3290
            if (wc_InitMutex(&clisession_mutex) != 0) {
3291
                WOLFSSL_MSG("Bad Init Mutex session");
3292
                ret = BAD_MUTEX_E;
3293
            }
3294
            else {
3295
                clisession_mutex_valid = 1;
3296
            }
3297
        }
3298
        #endif
3299
0
    #endif
3300
0
#endif
3301
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
3302
        /* OpenSSL registers cleanup using atexit */
3303
        if ((ret == WOLFSSL_SUCCESS) && (atexit(AtExitCleanup) != 0)) {
3304
            WOLFSSL_MSG("Bad atexit registration");
3305
            ret = WC_INIT_E;
3306
        }
3307
#endif
3308
0
    }
3309
3310
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3311
    /* System wide crypto policy disabled by default. */
3312
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
3313
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3314
3315
0
    if (ret == WOLFSSL_SUCCESS) {
3316
0
        initRefCount = initRefCount + 1;
3317
0
    }
3318
0
    else {
3319
0
        initRefCount = 1; /* Force cleanup */
3320
0
    }
3321
3322
0
    wc_UnLockMutex(&inits_count_mutex);
3323
3324
0
    if (ret != WOLFSSL_SUCCESS) {
3325
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
3326
0
    }
3327
3328
0
    return ret;
3329
0
}
3330
3331
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3332
/* Helper function for wolfSSL_crypto_policy_enable and
3333
 * wolfSSL_crypto_policy_enable_buffer.
3334
 *
3335
 * Parses the crypto policy string, verifies values,
3336
 * and sets in global crypto policy struct. Not thread
3337
 * safe. String length has already been verified.
3338
 *
3339
 * Returns WOLFSSL_SUCCESS on success.
3340
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
3341
 * Returns < 0 on misc error.
3342
 * */
3343
static int crypto_policy_parse(void)
3344
{
3345
    const char * hdr = WOLFSSL_SECLEVEL_STR;
3346
    int          sec_level = 0;
3347
    size_t       i = 0;
3348
3349
    /* All policies should begin with "@SECLEVEL=<N>" (N={0..5}) followed
3350
     * by bulk cipher list. */
3351
    if (XMEMCMP(crypto_policy.str, hdr, strlen(hdr)) != 0) {
3352
        WOLFSSL_MSG("error: crypto policy: invalid header");
3353
        return WOLFSSL_BAD_FILE;
3354
    }
3355
3356
    {
3357
        /* Extract the security level. */
3358
        char *       policy_mem = crypto_policy.str;
3359
        policy_mem += strlen(hdr);
3360
        sec_level = (int) (*policy_mem - '0');
3361
    }
3362
3363
    if (sec_level < MIN_WOLFSSL_SEC_LEVEL ||
3364
        sec_level > MAX_WOLFSSL_SEC_LEVEL) {
3365
        WOLFSSL_MSG_EX("error: invalid SECLEVEL: %d", sec_level);
3366
        return WOLFSSL_BAD_FILE;
3367
    }
3368
3369
    /* Remove trailing '\r' or '\n'. */
3370
    for (i = 0; i < MAX_WOLFSSL_CRYPTO_POLICY_SIZE; ++i) {
3371
        if (crypto_policy.str[i] == '\0') {
3372
            break;
3373
        }
3374
3375
        if (crypto_policy.str[i] == '\r' || crypto_policy.str[i] == '\n') {
3376
            crypto_policy.str[i] = '\0';
3377
            break;
3378
        }
3379
    }
3380
3381
    #if defined(DEBUG_WOLFSSL_VERBOSE)
3382
    WOLFSSL_MSG_EX("info: SECLEVEL=%d", sec_level);
3383
    WOLFSSL_MSG_EX("info: using crypto-policy file: %s, %ld", policy_file, sz);
3384
    #endif /* DEBUG_WOLFSSL_VERBOSE */
3385
3386
    crypto_policy.secLevel = sec_level;
3387
    crypto_policy.enabled = 1;
3388
3389
    return WOLFSSL_SUCCESS;
3390
}
3391
3392
#ifndef NO_FILESYSTEM
3393
/* Enables wolfSSL system wide crypto-policy, using the given policy
3394
 * file arg. If NULL is passed, then the default system crypto-policy
3395
 * file that was set at configure time will be used instead.
3396
 *
3397
 * While enabled:
3398
 *   - TLS methods, min key sizes, and cipher lists are all configured
3399
 *     automatically by the policy.
3400
 *   - Attempting to use lesser strength parameters will fail with
3401
 *     error CRYPTO_POLICY_FORBIDDEN.
3402
 *
3403
 * Disable with wolfSSL_crypto_policy_disable.
3404
 *
3405
 * Note: the wolfSSL_crypto_policy_X API are not thread safe, and should
3406
 * only be called at program init time.
3407
 *
3408
 * Returns WOLFSSL_SUCCESS on success.
3409
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
3410
 * Returns < 0 on misc error.
3411
 * */
3412
int wolfSSL_crypto_policy_enable(const char * policy_file)
3413
{
3414
    XFILE   file;
3415
    long    sz = 0;
3416
    size_t  n_read = 0;
3417
3418
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable");
3419
3420
    if (wolfSSL_crypto_policy_is_enabled()) {
3421
        WOLFSSL_MSG_EX("error: crypto policy already enabled: %s",
3422
                       policy_file);
3423
        return CRYPTO_POLICY_FORBIDDEN;
3424
    }
3425
3426
    if (policy_file == NULL) {
3427
        /* Use the configure-time default if NULL passed. */
3428
        policy_file = WC_STRINGIFY(WOLFSSL_CRYPTO_POLICY_FILE);
3429
    }
3430
3431
    if (policy_file == NULL || *policy_file == '\0') {
3432
        WOLFSSL_MSG("error: crypto policy empty file");
3433
        return BAD_FUNC_ARG;
3434
    }
3435
3436
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
3437
3438
    file = XFOPEN(policy_file, "rb");
3439
3440
    if (file == XBADFILE) {
3441
        WOLFSSL_MSG_EX("error: crypto policy file open failed: %s",
3442
                       policy_file);
3443
        return WOLFSSL_BAD_FILE;
3444
    }
3445
3446
    if (XFSEEK(file, 0, XSEEK_END) != 0) {
3447
        WOLFSSL_MSG_EX("error: crypto policy file seek end failed: %s",
3448
                       policy_file);
3449
        XFCLOSE(file);
3450
        return WOLFSSL_BAD_FILE;
3451
    }
3452
3453
    sz = XFTELL(file);
3454
3455
    if (XFSEEK(file, 0, XSEEK_SET) != 0) {
3456
        WOLFSSL_MSG_EX("error: crypto policy file seek failed: %s",
3457
                       policy_file);
3458
        XFCLOSE(file);
3459
        return WOLFSSL_BAD_FILE;
3460
    }
3461
3462
    if (sz <= 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
3463
        WOLFSSL_MSG_EX("error: crypto policy file %s, invalid size: %ld",
3464
                       policy_file, sz);
3465
        XFCLOSE(file);
3466
        return WOLFSSL_BAD_FILE;
3467
    }
3468
3469
    n_read = XFREAD(crypto_policy.str, 1, sz, file);
3470
    XFCLOSE(file);
3471
3472
    if (n_read != (size_t) sz) {
3473
        WOLFSSL_MSG_EX("error: crypto policy file %s: read %zu, "
3474
                       "expected %ld", policy_file, n_read, sz);
3475
        return WOLFSSL_BAD_FILE;
3476
    }
3477
3478
    crypto_policy.str[n_read] = '\0';
3479
3480
    return crypto_policy_parse();
3481
}
3482
#endif /* ! NO_FILESYSTEM */
3483
3484
/* Same behavior as wolfSSL_crypto_policy_enable, but loads
3485
 * via memory buf instead of file.
3486
 *
3487
 * Returns WOLFSSL_SUCCESS on success.
3488
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
3489
 * Returns < 0 on misc error.
3490
 * */
3491
int wolfSSL_crypto_policy_enable_buffer(const char * buf)
3492
{
3493
    size_t sz = 0;
3494
3495
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable_buffer");
3496
3497
    if (wolfSSL_crypto_policy_is_enabled()) {
3498
        WOLFSSL_MSG_EX("error: crypto policy already enabled");
3499
        return CRYPTO_POLICY_FORBIDDEN;
3500
    }
3501
3502
    if (buf == NULL || *buf == '\0') {
3503
        return BAD_FUNC_ARG;
3504
    }
3505
3506
    sz = XSTRLEN(buf);
3507
3508
    if (sz == 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
3509
        return BAD_FUNC_ARG;
3510
    }
3511
3512
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
3513
    XMEMCPY(crypto_policy.str, buf, sz);
3514
3515
    return crypto_policy_parse();
3516
}
3517
3518
/* Returns whether the system wide crypto-policy is enabled.
3519
 *
3520
 * Returns 1 if enabled.
3521
 *         0 if disabled.
3522
 * */
3523
int wolfSSL_crypto_policy_is_enabled(void)
3524
{
3525
    WOLFSSL_ENTER("wolfSSL_crypto_policy_is_enabled");
3526
3527
    return crypto_policy.enabled == 1;
3528
}
3529
3530
/* Disables the system wide crypto-policy.
3531
 * note: SSL and CTX structures already instantiated will
3532
 * keep their security policy parameters. This will only
3533
 * affect new instantiations.
3534
 * */
3535
void wolfSSL_crypto_policy_disable(void)
3536
{
3537
    WOLFSSL_ENTER("wolfSSL_crypto_policy_disable");
3538
    crypto_policy.enabled = 0;
3539
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
3540
    return;
3541
}
3542
3543
/* Get the crypto-policy bulk cipher list string.
3544
 * String is not owned by caller, should not be freed.
3545
 *
3546
 * Returns pointer to bulk cipher list string.
3547
 * Returns NULL if NOT enabled, or on error.
3548
 * */
3549
const char * wolfSSL_crypto_policy_get_ciphers(void)
3550
{
3551
    WOLFSSL_ENTER("wolfSSL_crypto_policy_get_ciphers");
3552
3553
    if (crypto_policy.enabled == 1) {
3554
        /* The crypto policy config will have
3555
         * this form:
3556
         *   "@SECLEVEL=2:kEECDH:kRSA..." */
3557
        return crypto_policy.str;
3558
    }
3559
3560
    return NULL;
3561
}
3562
3563
/* Get the configured crypto-policy security level.
3564
 * A security level of 0 does not impose any additional
3565
 * restrictions.
3566
 *
3567
 * Returns 1 - 5 if enabled.
3568
 * Returns 0 if NOT enabled.
3569
 * */
3570
int wolfSSL_crypto_policy_get_level(void)
3571
{
3572
    if (crypto_policy.enabled == 1) {
3573
        return crypto_policy.secLevel;
3574
    }
3575
3576
    return 0;
3577
}
3578
3579
/* Get security level from ssl structure.
3580
 * @param ssl  a pointer to WOLFSSL structure
3581
 */
3582
int wolfSSL_get_security_level(const WOLFSSL * ssl)
3583
{
3584
    if (ssl == NULL) {
3585
        return BAD_FUNC_ARG;
3586
    }
3587
3588
    return ssl->secLevel;
3589
}
3590
3591
#ifndef NO_WOLFSSL_STUB
3592
/*
3593
 * Set security level (wolfSSL doesn't support setting the security level).
3594
 *
3595
 * The security level can only be set through a system wide crypto-policy
3596
 * with wolfSSL_crypto_policy_enable().
3597
 *
3598
 * @param ssl  a pointer to WOLFSSL structure
3599
 * @param level security level
3600
 */
3601
void wolfSSL_set_security_level(WOLFSSL * ssl, int level)
3602
{
3603
    WOLFSSL_ENTER("wolfSSL_set_security_level");
3604
    (void)ssl;
3605
    (void)level;
3606
}
3607
#endif /* !NO_WOLFSSL_STUB */
3608
3609
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3610
3611
3612
#define WOLFSSL_SSL_LOAD_INCLUDED
3613
#include <src/ssl_load.c>
3614
3615
#define WOLFSSL_SSL_API_CRL_OCSP_INCLUDED
3616
#include "src/ssl_api_crl_ocsp.c"
3617
3618
3619
void wolfSSL_load_error_strings(void)
3620
0
{
3621
    /* compatibility only */
3622
0
}
3623
3624
3625
int wolfSSL_library_init(void)
3626
0
{
3627
0
    WOLFSSL_ENTER("wolfSSL_library_init");
3628
0
    if (wolfSSL_Init() == WOLFSSL_SUCCESS)
3629
0
        return WOLFSSL_SUCCESS;
3630
0
    else
3631
0
        return WOLFSSL_FATAL_ERROR;
3632
0
}
3633
3634
3635
#ifdef HAVE_SECRET_CALLBACK
3636
3637
int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx)
3638
{
3639
    WOLFSSL_ENTER("wolfSSL_set_session_secret_cb");
3640
    if (ssl == NULL)
3641
        return WOLFSSL_FAILURE;
3642
3643
    ssl->sessionSecretCb = cb;
3644
    ssl->sessionSecretCtx = ctx;
3645
    if (cb != NULL) {
3646
        /* If using a pre-set key, assume session resumption. */
3647
        ssl->session->sessionIDSz = 0;
3648
        ssl->options.resuming = 1;
3649
    }
3650
3651
    return WOLFSSL_SUCCESS;
3652
}
3653
3654
int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, TicketParseCb cb,
3655
        void *ctx)
3656
{
3657
    WOLFSSL_ENTER("wolfSSL_set_session_ticket_ext_cb");
3658
    if (ssl == NULL)
3659
        return WOLFSSL_FAILURE;
3660
3661
    ssl->ticketParseCb = cb;
3662
    ssl->ticketParseCtx = ctx;
3663
3664
    return WOLFSSL_SUCCESS;
3665
}
3666
3667
int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx)
3668
{
3669
    WOLFSSL_ENTER("wolfSSL_set_secret_cb");
3670
    if (ssl == NULL)
3671
        return WOLFSSL_FATAL_ERROR;
3672
3673
    ssl->tlsSecretCb = cb;
3674
    ssl->tlsSecretCtx = ctx;
3675
3676
    return WOLFSSL_SUCCESS;
3677
}
3678
3679
#ifdef SHOW_SECRETS
3680
int tlsShowSecrets(WOLFSSL* ssl, void* secret, int secretSz,
3681
        void* ctx)
3682
{
3683
    /* Wireshark Pre-Master-Secret Format:
3684
     *  CLIENT_RANDOM <clientrandom> <mastersecret>
3685
     */
3686
    const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
3687
    int i, pmsPos = 0;
3688
    char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
3689
    byte clientRandom[RAN_LEN];
3690
    int clientRandomSz;
3691
3692
    (void)ctx;
3693
3694
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
3695
        sizeof(clientRandom));
3696
3697
    if (clientRandomSz <= 0) {
3698
        printf("Error getting server random %d\n", clientRandomSz);
3699
        return BAD_FUNC_ARG;
3700
    }
3701
3702
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
3703
        CLIENT_RANDOM_LABEL);
3704
    pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
3705
    for (i = 0; i < clientRandomSz; i++) {
3706
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
3707
            clientRandom[i]);
3708
        pmsPos += 2;
3709
    }
3710
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
3711
    pmsPos += 1;
3712
    for (i = 0; i < secretSz; i++) {
3713
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
3714
            ((byte*)secret)[i]);
3715
        pmsPos += 2;
3716
    }
3717
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
3718
    pmsPos += 1;
3719
3720
    /* print master secret */
3721
    puts(pmsBuf);
3722
3723
    #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
3724
    {
3725
        FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
3726
        if (f != XBADFILE) {
3727
            XFWRITE(pmsBuf, 1, pmsPos, f);
3728
            XFCLOSE(f);
3729
        }
3730
    }
3731
    #endif
3732
    return 0;
3733
}
3734
#endif /* SHOW_SECRETS */
3735
3736
#endif
3737
3738
3739
#ifdef OPENSSL_EXTRA
3740
3741
/*
3742
 * check if the list has TLS13 and pre-TLS13 suites
3743
 * @param list cipher suite list that user want to set
3744
 *         (caller required to check for NULL)
3745
 * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
3746
 */
3747
static int CheckcipherList(const char* list)
3748
{
3749
    int ret;
3750
    int findTLSv13Suites = 0;
3751
    int findbeforeSuites = 0;
3752
    byte cipherSuite0;
3753
    byte cipherSuite1;
3754
    int flags;
3755
    char* next = (char*)list;
3756
3757
    do {
3758
        char*  current = next;
3759
        char   name[MAX_SUITE_NAME + 1];
3760
        word32 length = MAX_SUITE_NAME;
3761
        word32 current_length;
3762
        byte major = INVALID_BYTE;
3763
        byte minor = INVALID_BYTE;
3764
3765
        next   = XSTRSTR(next, ":");
3766
3767
        if (next) {
3768
            current_length = (word32)(next - current);
3769
            ++next; /* increment to skip ':' */
3770
        }
3771
        else {
3772
            current_length = (word32)XSTRLEN(current);
3773
        }
3774
3775
        if (current_length == 0) {
3776
            break;
3777
        }
3778
3779
        if (current_length < length) {
3780
            length = current_length;
3781
        }
3782
        XMEMCPY(name, current, length);
3783
        name[length] = 0;
3784
3785
        if (XSTRCMP(name, "ALL") == 0 ||
3786
            XSTRCMP(name, "DEFAULT") == 0 ||
3787
            XSTRCMP(name, "HIGH") == 0)
3788
        {
3789
            findTLSv13Suites = 1;
3790
            findbeforeSuites = 1;
3791
            break;
3792
        }
3793
3794
        ret = GetCipherSuiteFromName(name, &cipherSuite0,
3795
                &cipherSuite1, &major, &minor, &flags);
3796
        if (ret == 0) {
3797
            if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) {
3798
                /* TLSv13 suite */
3799
                findTLSv13Suites = 1;
3800
            }
3801
            else {
3802
                findbeforeSuites = 1;
3803
            }
3804
        }
3805
3806
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
3807
        /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */
3808
        if (ret != 0) {
3809
            char* subStr = name;
3810
            char* subStrNext;
3811
3812
            do {
3813
                subStrNext = XSTRSTR(subStr, "+");
3814
3815
                if ((XSTRCMP(subStr, "ECDHE") == 0) ||
3816
                    (XSTRCMP(subStr, "RSA") == 0)) {
3817
                    return 0;
3818
                }
3819
3820
                if (subStrNext && (XSTRLEN(subStrNext) > 0)) {
3821
                    subStr = subStrNext + 1; /* +1 to skip past '+' */
3822
                }
3823
            } while (subStrNext != NULL);
3824
        }
3825
    #endif
3826
3827
        if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
3828
            /* list has mixed suites */
3829
            return 0;
3830
        }
3831
    } while (next);
3832
3833
    if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
3834
        ret = 1;/* only before TLSv13 suites */
3835
    }
3836
    else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
3837
        ret = 2;/* only TLSv13 suties */
3838
    }
3839
    else {
3840
        ret = 0;/* handle as mixed */
3841
    }
3842
    return ret;
3843
}
3844
3845
/* parse some bulk lists like !eNULL / !aNULL
3846
 *
3847
 * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
3848
 */
3849
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
3850
        Suites* suites, const char* list)
3851
{
3852
    int     ret = 0;
3853
    int     listattribute = 0;
3854
    int     tls13Only = 0;
3855
    WC_DECLARE_VAR(suitesCpy, byte, WOLFSSL_MAX_SUITE_SZ, 0);
3856
    word16  suitesCpySz = 0;
3857
    word16  i = 0;
3858
    word16  j = 0;
3859
3860
    if (suites == NULL || list == NULL) {
3861
        WOLFSSL_MSG("NULL argument");
3862
        return WOLFSSL_FAILURE;
3863
    }
3864
3865
    listattribute = CheckcipherList(list);
3866
3867
    if (listattribute == 0) {
3868
       /* list has mixed(pre-TLSv13 and TLSv13) suites
3869
        * update cipher suites the same as before
3870
        */
3871
        return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS :
3872
        WOLFSSL_FAILURE;
3873
    }
3874
    else if (listattribute == 1) {
3875
       /* list has only pre-TLSv13 suites.
3876
        * Only update before TLSv13 suites.
3877
        */
3878
        tls13Only = 0;
3879
    }
3880
    else if (listattribute == 2) {
3881
       /* list has only TLSv13 suites. Only update TLv13 suites
3882
        * simulate set_ciphersuites() compatibility layer API
3883
        */
3884
        tls13Only = 1;
3885
        if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) ||
3886
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) {
3887
            /* Silently ignore TLS 1.3 ciphers if we don't support it. */
3888
            return WOLFSSL_SUCCESS;
3889
        }
3890
    }
3891
3892
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
3893
#ifdef WOLFSSL_SMALL_STACK
3894
    if (suites->suiteSz > 0) {
3895
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
3896
                DYNAMIC_TYPE_TMP_BUFFER);
3897
        if (suitesCpy == NULL) {
3898
            return WOLFSSL_FAILURE;
3899
        }
3900
3901
        XMEMSET(suitesCpy, 0, suites->suiteSz);
3902
    }
3903
#else
3904
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
3905
#endif
3906
3907
    if (suites->suiteSz > 0)
3908
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
3909
    suitesCpySz = suites->suiteSz;
3910
3911
    ret = SetCipherList_ex(ctx, ssl, suites, list);
3912
    if (ret != 1) {
3913
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3914
        return WOLFSSL_FAILURE;
3915
    }
3916
3917
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
3918
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
3919
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
3920
     * Since we direct both API here we attempt to provide API compatibility. If
3921
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
3922
     * suites and keep the suites from the other group.
3923
     * If downgrade is disabled, skip preserving the other group's suites. */
3924
    if ((ssl != NULL && !ssl->options.downgrade) ||
3925
        (ctx != NULL && !ctx->method->downgrade)) {
3926
        /* Downgrade disabled - don't preserve other group's suites */
3927
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3928
        return ret;
3929
    }
3930
3931
    for (i = 0; i < suitesCpySz &&
3932
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
3933
        /* Check for duplicates */
3934
        int duplicate = 0;
3935
        for (j = 0; j < suites->suiteSz; j += 2) {
3936
            if (suitesCpy[i] == suites->suites[j] &&
3937
                    suitesCpy[i+1] == suites->suites[j+1]) {
3938
                duplicate = 1;
3939
                break;
3940
            }
3941
        }
3942
        if (!duplicate) {
3943
            if (tls13Only) {
3944
                /* Updating TLS 1.3 ciphers */
3945
                if (suitesCpy[i] != TLS13_BYTE) {
3946
                    /* Only copy over <= TLS 1.2 ciphers */
3947
                    /* TLS 1.3 ciphers take precedence */
3948
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
3949
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
3950
                }
3951
            }
3952
            else {
3953
                /* Updating <= TLS 1.2 ciphers */
3954
                if (suitesCpy[i] == TLS13_BYTE) {
3955
                    /* Only copy over TLS 1.3 ciphers */
3956
                    /* TLS 1.3 ciphers take precedence */
3957
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
3958
                             suites->suiteSz);
3959
                    suites->suites[0] = suitesCpy[i];
3960
                    suites->suites[1] = suitesCpy[i+1];
3961
                    suites->suiteSz += 2;
3962
                }
3963
            }
3964
        }
3965
    }
3966
3967
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3968
    return ret;
3969
}
3970
3971
#endif
3972
3973
3974
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
3975
0
{
3976
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
3977
3978
0
    if (ctx == NULL)
3979
0
        return WOLFSSL_FAILURE;
3980
3981
0
    if (AllocateCtxSuites(ctx) != 0)
3982
0
        return WOLFSSL_FAILURE;
3983
3984
#ifdef OPENSSL_EXTRA
3985
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
3986
#else
3987
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
3988
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3989
0
#endif
3990
0
}
3991
3992
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
3993
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
3994
                                      const int listSz)
3995
{
3996
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
3997
3998
    if (ctx == NULL)
3999
        return WOLFSSL_FAILURE;
4000
4001
    if (AllocateCtxSuites(ctx) != 0)
4002
        return WOLFSSL_FAILURE;
4003
4004
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
4005
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
4006
}
4007
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
4008
4009
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
4010
0
{
4011
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
4012
4013
0
    if (ssl == NULL || ssl->ctx == NULL) {
4014
0
        return WOLFSSL_FAILURE;
4015
0
    }
4016
4017
0
    if (AllocateSuites(ssl) != 0)
4018
0
        return WOLFSSL_FAILURE;
4019
4020
#ifdef OPENSSL_EXTRA
4021
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
4022
#else
4023
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
4024
0
        WOLFSSL_SUCCESS :
4025
0
        WOLFSSL_FAILURE;
4026
0
#endif
4027
0
}
4028
4029
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
4030
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
4031
                                  const int listSz)
4032
{
4033
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
4034
4035
    if (ssl == NULL || ssl->ctx == NULL) {
4036
        return WOLFSSL_FAILURE;
4037
    }
4038
4039
    if (AllocateSuites(ssl) != 0)
4040
        return WOLFSSL_FAILURE;
4041
4042
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
4043
           ? WOLFSSL_SUCCESS
4044
           : WOLFSSL_FAILURE;
4045
}
4046
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
4047
4048
4049
#ifdef HAVE_KEYING_MATERIAL
4050
4051
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
4052
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
4053
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
4054
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
4055
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
4056
4057
static const struct ForbiddenLabels {
4058
    const char* label;
4059
    size_t labelLen;
4060
} forbiddenLabels[] = {
4061
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
4062
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
4063
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
4064
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
4065
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
4066
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
4067
    {NULL, 0},
4068
};
4069
4070
/**
4071
 * Implement RFC 5705
4072
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
4073
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
4074
 */
4075
int wolfSSL_export_keying_material(WOLFSSL *ssl,
4076
        unsigned char *out, size_t outLen,
4077
        const char *label, size_t labelLen,
4078
        const unsigned char *context, size_t contextLen,
4079
        int use_context)
4080
{
4081
    byte*  seed = NULL;
4082
    word32 seedLen;
4083
    const struct ForbiddenLabels* fl;
4084
4085
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
4086
4087
    if (ssl == NULL || out == NULL || label == NULL ||
4088
            (use_context && contextLen && context == NULL)) {
4089
        WOLFSSL_MSG("Bad argument");
4090
        return WOLFSSL_FAILURE;
4091
    }
4092
4093
    /* Sanity check contextLen to prevent integer overflow when cast to word32
4094
     * and to ensure it fits in the 2-byte length encoding (max 65535). */
4095
    if (use_context && contextLen > WOLFSSL_MAX_16BIT) {
4096
        WOLFSSL_MSG("contextLen too large");
4097
        return WOLFSSL_FAILURE;
4098
    }
4099
4100
    /* clientRandom + serverRandom
4101
     * OR
4102
     * clientRandom + serverRandom + ctx len encoding + ctx */
4103
    seedLen = !use_context ? (word32)SEED_LEN :
4104
                             (word32)SEED_LEN + 2 + (word32)contextLen;
4105
4106
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
4107
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
4108
                    "data. Call wolfSSL_KeepArrays before attempting to "
4109
                    "export keyid material.");
4110
        return WOLFSSL_FAILURE;
4111
    }
4112
4113
    /* check forbidden labels */
4114
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
4115
        if (labelLen >= fl->labelLen &&
4116
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
4117
            WOLFSSL_MSG("Forbidden label");
4118
            return WOLFSSL_FAILURE;
4119
        }
4120
    }
4121
4122
#ifdef WOLFSSL_TLS13
4123
    if (IsAtLeastTLSv1_3(ssl->version)) {
4124
        /* Path for TLS 1.3 */
4125
        if (!use_context) {
4126
            contextLen = 0;
4127
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
4128
        }
4129
4130
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
4131
                context, contextLen) != 0) {
4132
            WOLFSSL_MSG("Tls13_Exporter error");
4133
            return WOLFSSL_FAILURE;
4134
        }
4135
        return WOLFSSL_SUCCESS;
4136
    }
4137
#endif
4138
4139
    /* Path for <=TLS 1.2 */
4140
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4141
    if (seed == NULL) {
4142
        WOLFSSL_MSG("malloc error");
4143
        return WOLFSSL_FAILURE;
4144
    }
4145
4146
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
4147
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
4148
4149
    if (use_context) {
4150
        /* Encode len in big endian */
4151
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
4152
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
4153
        if (contextLen) {
4154
            /* 0 length context is allowed */
4155
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
4156
        }
4157
    }
4158
4159
    PRIVATE_KEY_UNLOCK();
4160
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
4161
            (byte*)label, (word32)labelLen, seed, seedLen,
4162
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
4163
            ssl->devId) != 0) {
4164
        WOLFSSL_MSG("wc_PRF_TLS error");
4165
        PRIVATE_KEY_LOCK();
4166
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4167
        return WOLFSSL_FAILURE;
4168
    }
4169
    PRIVATE_KEY_LOCK();
4170
4171
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4172
    return WOLFSSL_SUCCESS;
4173
}
4174
#endif /* HAVE_KEYING_MATERIAL */
4175
4176
4177
/* EITHER SIDE METHODS */
4178
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
4179
    WOLFSSL_METHOD* wolfSSLv23_method(void)
4180
    {
4181
        return wolfSSLv23_method_ex(NULL);
4182
    }
4183
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
4184
    {
4185
        WOLFSSL_METHOD* m = NULL;
4186
        WOLFSSL_ENTER("wolfSSLv23_method");
4187
    #if !defined(NO_WOLFSSL_CLIENT)
4188
        m = wolfSSLv23_client_method_ex(heap);
4189
    #elif !defined(NO_WOLFSSL_SERVER)
4190
        m = wolfSSLv23_server_method_ex(heap);
4191
    #else
4192
        (void)heap;
4193
    #endif
4194
        if (m != NULL) {
4195
            m->side = WOLFSSL_NEITHER_END;
4196
        }
4197
4198
        return m;
4199
    }
4200
4201
    #ifndef NO_OLD_TLS
4202
    #ifdef WOLFSSL_ALLOW_SSLV3
4203
    WOLFSSL_METHOD* wolfSSLv3_method(void)
4204
    {
4205
        return wolfSSLv3_method_ex(NULL);
4206
    }
4207
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
4208
    {
4209
        WOLFSSL_METHOD* m = NULL;
4210
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
4211
    #if !defined(NO_WOLFSSL_CLIENT)
4212
        m = wolfSSLv3_client_method_ex(heap);
4213
    #elif !defined(NO_WOLFSSL_SERVER)
4214
        m = wolfSSLv3_server_method_ex(heap);
4215
    #endif
4216
        if (m != NULL) {
4217
            m->side = WOLFSSL_NEITHER_END;
4218
        }
4219
4220
        return m;
4221
    }
4222
    #endif
4223
    #endif
4224
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
4225
4226
/* client only parts */
4227
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
4228
4229
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
4230
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
4231
    {
4232
        WOLFSSL_STUB("wolfSSLv2_client_method");
4233
        return NULL;
4234
    }
4235
    #endif
4236
4237
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4238
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
4239
    {
4240
        return wolfSSLv3_client_method_ex(NULL);
4241
    }
4242
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
4243
    {
4244
        WOLFSSL_METHOD* method =
4245
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4246
                                                     heap, DYNAMIC_TYPE_METHOD);
4247
        (void)heap;
4248
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
4249
        if (method)
4250
            InitSSL_Method(method, MakeSSLv3());
4251
        return method;
4252
    }
4253
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
4254
4255
4256
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
4257
0
    {
4258
0
        return wolfSSLv23_client_method_ex(NULL);
4259
0
    }
4260
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
4261
0
    {
4262
0
        WOLFSSL_METHOD* method =
4263
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4264
0
                                                     heap, DYNAMIC_TYPE_METHOD);
4265
0
        (void)heap;
4266
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
4267
0
        if (method) {
4268
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
4269
0
        defined(WOLFSSL_SHA512)
4270
0
        #if defined(WOLFSSL_TLS13)
4271
0
            InitSSL_Method(method, MakeTLSv1_3());
4272
        #elif !defined(WOLFSSL_NO_TLS12)
4273
            InitSSL_Method(method, MakeTLSv1_2());
4274
        #elif !defined(NO_OLD_TLS)
4275
            InitSSL_Method(method, MakeTLSv1_1());
4276
        #endif
4277
    #else
4278
        #ifndef NO_OLD_TLS
4279
            InitSSL_Method(method, MakeTLSv1_1());
4280
        #endif
4281
    #endif
4282
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
4283
0
            method->downgrade = 1;
4284
0
    #endif
4285
0
        }
4286
0
        return method;
4287
0
    }
4288
4289
    /* please see note at top of README if you get an error from connect */
4290
    WOLFSSL_ABI
4291
    int wolfSSL_connect(WOLFSSL* ssl)
4292
0
    {
4293
0
    #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4294
0
          defined(WOLFSSL_TLS13))
4295
0
        int neededState;
4296
0
        byte advanceState;
4297
0
    #endif
4298
0
        int ret = 0;
4299
4300
0
        (void)ret;
4301
4302
0
        #ifdef HAVE_ERRNO_H
4303
0
            errno = 0;
4304
0
        #endif
4305
4306
0
        if (ssl == NULL)
4307
0
            return BAD_FUNC_ARG;
4308
4309
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
4310
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
4311
            ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
4312
            if (ssl->error != WOLFSSL_SUCCESS) {
4313
                WOLFSSL_ERROR(ssl->error);
4314
                return WOLFSSL_FATAL_ERROR;
4315
            }
4316
            ssl->error = 0; /* expected to be zero here */
4317
        }
4318
4319
    #ifdef OPENSSL_EXTRA
4320
        if (ssl->CBIS != NULL) {
4321
            ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS);
4322
            ssl->cbmode = WOLFSSL_CB_WRITE;
4323
        }
4324
    #endif
4325
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
4326
4327
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4328
        defined(WOLFSSL_TLS13)
4329
        return wolfSSL_connect_TLSv13(ssl);
4330
    #else
4331
0
        #ifdef WOLFSSL_TLS13
4332
0
        if (ssl->options.tls1_3) {
4333
0
            WOLFSSL_MSG("TLS 1.3");
4334
0
            return wolfSSL_connect_TLSv13(ssl);
4335
0
        }
4336
0
        #endif
4337
4338
0
        WOLFSSL_MSG("TLS 1.2 or lower");
4339
0
        WOLFSSL_ENTER("wolfSSL_connect");
4340
4341
        /* make sure this wolfSSL object has arrays and rng setup. Protects
4342
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
4343
0
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
4344
0
            return ret;
4345
0
        }
4346
4347
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
4348
        if ((ssl->ConnectFilter != NULL) &&
4349
            (ssl->options.connectState == CONNECT_BEGIN)) {
4350
            wolfSSL_netfilter_decision_t res;
4351
            if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
4352
                 WOLFSSL_SUCCESS) &&
4353
                (res == WOLFSSL_NETFILTER_REJECT)) {
4354
                ssl->error = SOCKET_FILTERED_E;
4355
                WOLFSSL_ERROR(ssl->error);
4356
                return WOLFSSL_FATAL_ERROR;
4357
            }
4358
        }
4359
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
4360
4361
0
        if (ssl->options.side != WOLFSSL_CLIENT_END) {
4362
0
            ssl->error = SIDE_ERROR;
4363
0
            WOLFSSL_ERROR(ssl->error);
4364
0
            return WOLFSSL_FATAL_ERROR;
4365
0
        }
4366
4367
        #ifdef WOLFSSL_DTLS
4368
        if (ssl->version.major == DTLS_MAJOR) {
4369
            ssl->options.dtls   = 1;
4370
            ssl->options.tls    = 1;
4371
            ssl->options.tls1_1 = 1;
4372
            ssl->options.dtlsStateful = 1;
4373
        }
4374
        #endif
4375
4376
        /* fragOffset is non-zero when sending fragments. On the last
4377
         * fragment, fragOffset is zero again, and the state can be
4378
         * advanced. */
4379
0
        advanceState = ssl->fragOffset == 0 &&
4380
0
            (ssl->options.connectState == CONNECT_BEGIN ||
4381
0
             ssl->options.connectState == HELLO_AGAIN ||
4382
0
             (ssl->options.connectState >= FIRST_REPLY_DONE &&
4383
0
              ssl->options.connectState <= FIRST_REPLY_FOURTH));
4384
4385
#ifdef WOLFSSL_DTLS13
4386
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
4387
            advanceState = advanceState && !ssl->dtls13SendingAckOrRtx;
4388
#endif /* WOLFSSL_DTLS13 */
4389
4390
0
        if (ssl->buffers.outputBuffer.length > 0
4391
        #ifdef WOLFSSL_ASYNC_CRYPT
4392
            /* do not send buffered or advance state if last error was an
4393
                async pending operation */
4394
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
4395
        #endif
4396
0
        ) {
4397
0
            ret = SendBuffered(ssl);
4398
0
            if (ret == 0) {
4399
0
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
4400
0
                    if (advanceState) {
4401
0
                        ssl->options.connectState++;
4402
0
                        WOLFSSL_MSG("connect state: Advanced from last "
4403
0
                                    "buffered fragment send");
4404
0
                    #ifdef WOLFSSL_ASYNC_IO
4405
                        /* Cleanup async */
4406
0
                        FreeAsyncCtx(ssl, 0);
4407
0
                    #endif
4408
0
                    }
4409
0
                }
4410
0
                else {
4411
0
                    WOLFSSL_MSG("connect state: "
4412
0
                                "Not advanced, more fragments to send");
4413
0
                }
4414
0
            }
4415
0
            else {
4416
0
                ssl->error = ret;
4417
0
                WOLFSSL_ERROR(ssl->error);
4418
0
                return WOLFSSL_FATAL_ERROR;
4419
0
            }
4420
#ifdef WOLFSSL_DTLS13
4421
            if (ssl->options.dtls)
4422
                ssl->dtls13SendingAckOrRtx = 0;
4423
#endif /* WOLFSSL_DTLS13 */
4424
0
        }
4425
4426
0
        ret = RetrySendAlert(ssl);
4427
0
        if (ret != 0) {
4428
0
            ssl->error = ret;
4429
0
            WOLFSSL_ERROR(ssl->error);
4430
0
            return WOLFSSL_FATAL_ERROR;
4431
0
        }
4432
4433
0
        switch (ssl->options.connectState) {
4434
4435
0
        case CONNECT_BEGIN :
4436
            /* always send client hello first */
4437
0
            if ( (ssl->error = SendClientHello(ssl)) != 0) {
4438
0
                WOLFSSL_ERROR(ssl->error);
4439
0
                return WOLFSSL_FATAL_ERROR;
4440
0
            }
4441
0
            ssl->options.connectState = CLIENT_HELLO_SENT;
4442
0
            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
4443
0
            FALL_THROUGH;
4444
4445
0
        case CLIENT_HELLO_SENT :
4446
0
            neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
4447
0
                                          SERVER_HELLODONE_COMPLETE;
4448
            #ifdef WOLFSSL_DTLS
4449
                /* In DTLS, when resuming, we can go straight to FINISHED,
4450
                 * or do a cookie exchange and then skip to FINISHED, assume
4451
                 * we need the cookie exchange first. */
4452
                if (IsDtlsNotSctpMode(ssl))
4453
                    neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
4454
            #endif
4455
            /* get response */
4456
0
            WOLFSSL_MSG("Server state up to needed state.");
4457
0
            while (ssl->options.serverState < neededState) {
4458
0
                WOLFSSL_MSG("Progressing server state...");
4459
0
                #ifdef WOLFSSL_TLS13
4460
0
                    if (ssl->options.tls1_3)
4461
0
                        return wolfSSL_connect_TLSv13(ssl);
4462
0
                #endif
4463
0
                WOLFSSL_MSG("ProcessReply...");
4464
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
4465
0
                    WOLFSSL_ERROR(ssl->error);
4466
0
                    return WOLFSSL_FATAL_ERROR;
4467
0
                }
4468
                /* if resumption failed, reset needed state */
4469
0
                else if (neededState == SERVER_FINISHED_COMPLETE) {
4470
0
                    if (!ssl->options.resuming) {
4471
                    #ifdef WOLFSSL_DTLS
4472
                        if (IsDtlsNotSctpMode(ssl))
4473
                            neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
4474
                        else
4475
                    #endif
4476
0
                            neededState = SERVER_HELLODONE_COMPLETE;
4477
0
                    }
4478
0
                }
4479
0
                WOLFSSL_MSG("ProcessReply done.");
4480
4481
#ifdef WOLFSSL_DTLS13
4482
                if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)
4483
                    && ssl->dtls13Rtx.sendAcks == 1
4484
                    && ssl->options.seenUnifiedHdr) {
4485
                    /* we aren't negotiated the version yet, so we aren't sure
4486
                     * the other end can speak v1.3. On the other side we have
4487
                     * received a unified records, assuming that the
4488
                     * ServerHello got lost, we will send an empty ACK. In case
4489
                     * the server is a DTLS with version less than 1.3, it
4490
                     * should just ignore the message */
4491
                    ssl->dtls13Rtx.sendAcks = 0;
4492
                    if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
4493
                        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4494
                            ssl->dtls13SendingAckOrRtx = 1;
4495
                        WOLFSSL_ERROR(ssl->error);
4496
                        return WOLFSSL_FATAL_ERROR;
4497
                    }
4498
                }
4499
#endif /* WOLFSSL_DTLS13 */
4500
0
            }
4501
4502
0
            ssl->options.connectState = HELLO_AGAIN;
4503
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
4504
0
            FALL_THROUGH;
4505
4506
0
        case HELLO_AGAIN :
4507
4508
0
        #ifdef WOLFSSL_TLS13
4509
0
            if (ssl->options.tls1_3)
4510
0
                return wolfSSL_connect_TLSv13(ssl);
4511
0
        #endif
4512
4513
            #ifdef WOLFSSL_DTLS
4514
            if (ssl->options.serverState ==
4515
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
4516
                if (IsDtlsNotSctpMode(ssl)) {
4517
                    /* re-init hashes, exclude first hello and verify request */
4518
                    if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
4519
                        WOLFSSL_ERROR(ssl->error);
4520
                        return WOLFSSL_FATAL_ERROR;
4521
                    }
4522
                    if ( (ssl->error = SendClientHello(ssl)) != 0) {
4523
                        WOLFSSL_ERROR(ssl->error);
4524
                        return WOLFSSL_FATAL_ERROR;
4525
                    }
4526
                }
4527
            }
4528
            #endif
4529
4530
0
            ssl->options.connectState = HELLO_AGAIN_REPLY;
4531
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
4532
0
            FALL_THROUGH;
4533
4534
0
        case HELLO_AGAIN_REPLY :
4535
            #ifdef WOLFSSL_DTLS
4536
                if (IsDtlsNotSctpMode(ssl)) {
4537
                    neededState = ssl->options.resuming ?
4538
                           SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
4539
4540
                    /* get response */
4541
                    while (ssl->options.serverState < neededState) {
4542
                        if ( (ssl->error = ProcessReply(ssl)) < 0) {
4543
                            WOLFSSL_ERROR(ssl->error);
4544
                            return WOLFSSL_FATAL_ERROR;
4545
                        }
4546
                        /* if resumption failed, reset needed state */
4547
                        if (neededState == SERVER_FINISHED_COMPLETE) {
4548
                            if (!ssl->options.resuming)
4549
                                neededState = SERVER_HELLODONE_COMPLETE;
4550
                        }
4551
                    }
4552
                }
4553
            #endif
4554
4555
0
            ssl->options.connectState = FIRST_REPLY_DONE;
4556
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
4557
0
            FALL_THROUGH;
4558
4559
0
        case FIRST_REPLY_DONE :
4560
0
            if (ssl->options.certOnly)
4561
0
                return WOLFSSL_SUCCESS;
4562
0
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
4563
0
                #ifdef WOLFSSL_TLS13
4564
0
                    if (ssl->options.tls1_3)
4565
0
                        return wolfSSL_connect_TLSv13(ssl);
4566
0
                #endif
4567
0
                if (ssl->options.sendVerify) {
4568
0
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
4569
0
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4570
0
                        WOLFSSL_ERROR(ssl->error);
4571
0
                        return WOLFSSL_FATAL_ERROR;
4572
0
                    }
4573
0
                    WOLFSSL_MSG("sent: certificate");
4574
0
                }
4575
4576
0
            #endif
4577
0
            ssl->options.connectState = FIRST_REPLY_FIRST;
4578
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
4579
0
            FALL_THROUGH;
4580
4581
0
        case FIRST_REPLY_FIRST :
4582
0
        #ifdef WOLFSSL_TLS13
4583
0
            if (ssl->options.tls1_3)
4584
0
                return wolfSSL_connect_TLSv13(ssl);
4585
0
        #endif
4586
0
            if (!ssl->options.resuming) {
4587
0
                if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
4588
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4589
#ifdef WOLFSSL_EXTRA_ALERTS
4590
                    if (ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY) ||
4591
                        ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) {
4592
                        SendAlert(ssl, alert_fatal, handshake_failure);
4593
                    }
4594
#endif
4595
0
                    WOLFSSL_ERROR(ssl->error);
4596
0
                    return WOLFSSL_FATAL_ERROR;
4597
0
                }
4598
0
                WOLFSSL_MSG("sent: client key exchange");
4599
0
            }
4600
4601
0
            ssl->options.connectState = FIRST_REPLY_SECOND;
4602
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
4603
0
            FALL_THROUGH;
4604
4605
0
    #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
4606
0
        case FIRST_REPLY_SECOND :
4607
            /* CLIENT: Fail-safe for Server Authentication. */
4608
0
            if (!ssl->options.peerAuthGood) {
4609
0
                WOLFSSL_MSG("Server authentication did not happen");
4610
0
                ssl->error = NO_PEER_VERIFY;
4611
0
                return WOLFSSL_FATAL_ERROR;
4612
0
            }
4613
4614
0
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
4615
0
                if (ssl->options.sendVerify) {
4616
0
                    if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
4617
0
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4618
0
                        WOLFSSL_ERROR(ssl->error);
4619
0
                        return WOLFSSL_FATAL_ERROR;
4620
0
                    }
4621
0
                    WOLFSSL_MSG("sent: certificate verify");
4622
0
                }
4623
0
            #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
4624
0
            ssl->options.connectState = FIRST_REPLY_THIRD;
4625
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
4626
0
            FALL_THROUGH;
4627
4628
0
        case FIRST_REPLY_THIRD :
4629
0
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
4630
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4631
0
                WOLFSSL_ERROR(ssl->error);
4632
0
                return WOLFSSL_FATAL_ERROR;
4633
0
            }
4634
0
            WOLFSSL_MSG("sent: change cipher spec");
4635
0
            ssl->options.connectState = FIRST_REPLY_FOURTH;
4636
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
4637
0
            FALL_THROUGH;
4638
4639
0
        case FIRST_REPLY_FOURTH :
4640
0
            if ( (ssl->error = SendFinished(ssl)) != 0) {
4641
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4642
0
                WOLFSSL_ERROR(ssl->error);
4643
0
                return WOLFSSL_FATAL_ERROR;
4644
0
            }
4645
0
            WOLFSSL_MSG("sent: finished");
4646
0
            ssl->options.connectState = FINISHED_DONE;
4647
0
            WOLFSSL_MSG("connect state: FINISHED_DONE");
4648
0
            FALL_THROUGH;
4649
4650
#ifdef WOLFSSL_DTLS13
4651
        case WAIT_FINISHED_ACK:
4652
            ssl->options.connectState = FINISHED_DONE;
4653
            FALL_THROUGH;
4654
#endif /* WOLFSSL_DTLS13 */
4655
4656
0
        case FINISHED_DONE :
4657
            /* get response */
4658
0
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
4659
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
4660
0
                    WOLFSSL_ERROR(ssl->error);
4661
0
                    return WOLFSSL_FATAL_ERROR;
4662
0
                }
4663
4664
0
            ssl->options.connectState = SECOND_REPLY_DONE;
4665
0
            WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
4666
0
            FALL_THROUGH;
4667
4668
0
        case SECOND_REPLY_DONE:
4669
0
        #ifndef NO_HANDSHAKE_DONE_CB
4670
0
            if (ssl->hsDoneCb) {
4671
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
4672
0
                if (cbret < 0) {
4673
0
                    ssl->error = cbret;
4674
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
4675
0
                    return WOLFSSL_FATAL_ERROR;
4676
0
                }
4677
0
            }
4678
0
        #endif /* NO_HANDSHAKE_DONE_CB */
4679
4680
0
            if (!ssl->options.dtls) {
4681
0
                if (!ssl->options.keepResources) {
4682
0
                    FreeHandshakeResources(ssl);
4683
0
                }
4684
0
            }
4685
        #ifdef WOLFSSL_DTLS
4686
            else {
4687
                ssl->options.dtlsHsRetain = 1;
4688
            }
4689
        #endif /* WOLFSSL_DTLS */
4690
4691
        #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
4692
            /* This may be necessary in async so that we don't try to
4693
             * renegotiate again */
4694
            if (ssl->secure_renegotiation &&
4695
                    ssl->secure_renegotiation->startScr) {
4696
                ssl->secure_renegotiation->startScr = 0;
4697
            }
4698
        #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
4699
0
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
4700
            /* Free the remaining async context if not using it for crypto */
4701
0
            FreeAsyncCtx(ssl, 1);
4702
0
        #endif
4703
4704
0
            ssl->error = 0; /* clear the error */
4705
4706
0
            WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
4707
0
            return WOLFSSL_SUCCESS;
4708
0
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
4709
4710
0
        default:
4711
0
            WOLFSSL_MSG("Unknown connect state ERROR");
4712
0
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
4713
0
        }
4714
0
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
4715
0
    }
4716
4717
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
4718
/* end client only parts */
4719
4720
/* server only parts */
4721
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
4722
4723
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
4724
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
4725
    {
4726
        WOLFSSL_STUB("wolfSSLv2_server_method");
4727
        return 0;
4728
    }
4729
    #endif
4730
4731
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4732
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
4733
    {
4734
        return wolfSSLv3_server_method_ex(NULL);
4735
    }
4736
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
4737
    {
4738
        WOLFSSL_METHOD* method =
4739
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4740
                                                     heap, DYNAMIC_TYPE_METHOD);
4741
        (void)heap;
4742
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
4743
        if (method) {
4744
            InitSSL_Method(method, MakeSSLv3());
4745
            method->side = WOLFSSL_SERVER_END;
4746
        }
4747
        return method;
4748
    }
4749
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
4750
4751
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
4752
0
    {
4753
0
        return wolfSSLv23_server_method_ex(NULL);
4754
0
    }
4755
4756
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
4757
0
    {
4758
0
        WOLFSSL_METHOD* method =
4759
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4760
0
                                                     heap, DYNAMIC_TYPE_METHOD);
4761
0
        (void)heap;
4762
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
4763
0
        if (method) {
4764
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
4765
0
        defined(WOLFSSL_SHA512)
4766
0
        #ifdef WOLFSSL_TLS13
4767
0
            InitSSL_Method(method, MakeTLSv1_3());
4768
        #elif !defined(WOLFSSL_NO_TLS12)
4769
            InitSSL_Method(method, MakeTLSv1_2());
4770
        #elif !defined(NO_OLD_TLS)
4771
            InitSSL_Method(method, MakeTLSv1_1());
4772
        #endif
4773
    #else
4774
        #ifndef NO_OLD_TLS
4775
            InitSSL_Method(method, MakeTLSv1_1());
4776
        #else
4777
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
4778
        #endif
4779
    #endif
4780
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
4781
0
            method->downgrade = 1;
4782
0
    #endif
4783
0
            method->side      = WOLFSSL_SERVER_END;
4784
0
        }
4785
0
        return method;
4786
0
    }
4787
4788
4789
    WOLFSSL_ABI
4790
    int wolfSSL_accept(WOLFSSL* ssl)
4791
0
    {
4792
0
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4793
0
    defined(WOLFSSL_TLS13))
4794
0
        word16 havePSK = 0;
4795
0
        word16 haveAnon = 0;
4796
0
        word16 haveMcast = 0;
4797
0
#endif
4798
0
        int ret = 0;
4799
4800
0
        (void)ret;
4801
4802
0
        if (ssl == NULL)
4803
0
            return WOLFSSL_FATAL_ERROR;
4804
4805
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
4806
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
4807
            WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
4808
            ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
4809
            if (ssl->error != WOLFSSL_SUCCESS) {
4810
                WOLFSSL_ERROR(ssl->error);
4811
                return WOLFSSL_FATAL_ERROR;
4812
            }
4813
            ssl->error = 0; /* expected to be zero here */
4814
        }
4815
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
4816
4817
#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
4818
        return wolfSSL_accept_TLSv13(ssl);
4819
#else
4820
0
    #ifdef WOLFSSL_TLS13
4821
0
        if (ssl->options.tls1_3)
4822
0
            return wolfSSL_accept_TLSv13(ssl);
4823
0
    #endif
4824
0
        WOLFSSL_ENTER("wolfSSL_accept");
4825
4826
        /* make sure this wolfSSL object has arrays and rng setup. Protects
4827
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
4828
0
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
4829
0
            return ret;
4830
0
        }
4831
4832
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
4833
        if ((ssl->AcceptFilter != NULL) &&
4834
            ((ssl->options.acceptState == ACCEPT_BEGIN)
4835
#ifdef HAVE_SECURE_RENEGOTIATION
4836
             || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
4837
#endif
4838
                ))
4839
        {
4840
            wolfSSL_netfilter_decision_t res;
4841
            if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
4842
                 WOLFSSL_SUCCESS) &&
4843
                (res == WOLFSSL_NETFILTER_REJECT)) {
4844
                ssl->error = SOCKET_FILTERED_E;
4845
                WOLFSSL_ERROR(ssl->error);
4846
                return WOLFSSL_FATAL_ERROR;
4847
            }
4848
        }
4849
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
4850
4851
0
        #ifdef HAVE_ERRNO_H
4852
0
            errno = 0;
4853
0
        #endif
4854
4855
        #ifndef NO_PSK
4856
            havePSK = ssl->options.havePSK;
4857
        #endif
4858
0
        (void)havePSK;
4859
4860
        #ifdef HAVE_ANON
4861
            haveAnon = ssl->options.useAnon;
4862
        #endif
4863
0
        (void)haveAnon;
4864
4865
        #ifdef WOLFSSL_MULTICAST
4866
            haveMcast = ssl->options.haveMcast;
4867
        #endif
4868
0
        (void)haveMcast;
4869
4870
0
        if (ssl->options.side != WOLFSSL_SERVER_END) {
4871
0
            ssl->error = SIDE_ERROR;
4872
0
            WOLFSSL_ERROR(ssl->error);
4873
0
            return WOLFSSL_FATAL_ERROR;
4874
0
        }
4875
4876
0
    #ifndef NO_CERTS
4877
        /* in case used set_accept_state after init */
4878
0
        if (!havePSK && !haveAnon && !haveMcast) {
4879
        #ifdef WOLFSSL_CERT_SETUP_CB
4880
            if (ssl->ctx->certSetupCb != NULL) {
4881
                WOLFSSL_MSG("CertSetupCb set. server cert and "
4882
                            "key not checked");
4883
            }
4884
            else
4885
        #endif
4886
0
            {
4887
0
                if (!ssl->buffers.certificate ||
4888
0
                    !ssl->buffers.certificate->buffer) {
4889
4890
0
                    WOLFSSL_MSG("accept error: server cert required");
4891
0
                    ssl->error = NO_PRIVATE_KEY;
4892
0
                    WOLFSSL_ERROR(ssl->error);
4893
0
                    return WOLFSSL_FATAL_ERROR;
4894
0
                }
4895
4896
0
                if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
4897
                    /* allow no private key if using existing key */
4898
                #ifdef WOLF_PRIVATE_KEY_ID
4899
                    if (ssl->devId != INVALID_DEVID
4900
                    #ifdef HAVE_PK_CALLBACKS
4901
                        || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
4902
                    #endif
4903
                    ) {
4904
                        WOLFSSL_MSG("Allowing no server private key "
4905
                                    "(external)");
4906
                    }
4907
                    else
4908
                #endif
4909
0
                    {
4910
0
                        WOLFSSL_MSG("accept error: server key required");
4911
0
                        ssl->error = NO_PRIVATE_KEY;
4912
0
                        WOLFSSL_ERROR(ssl->error);
4913
0
                        return WOLFSSL_FATAL_ERROR;
4914
0
                    }
4915
0
                }
4916
0
            }
4917
0
        }
4918
0
    #endif
4919
4920
    #ifdef WOLFSSL_DTLS
4921
        if (ssl->version.major == DTLS_MAJOR) {
4922
            ssl->options.dtls   = 1;
4923
            ssl->options.tls    = 1;
4924
            ssl->options.tls1_1 = 1;
4925
            if (!IsDtlsNotSctpMode(ssl) || IsSCR(ssl))
4926
                ssl->options.dtlsStateful = 1;
4927
        }
4928
    #endif
4929
4930
0
        if (ssl->buffers.outputBuffer.length > 0
4931
        #ifdef WOLFSSL_ASYNC_CRYPT
4932
            /* do not send buffered or advance state if last error was an
4933
                async pending operation */
4934
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
4935
        #endif
4936
0
        ) {
4937
0
            ret = SendBuffered(ssl);
4938
0
            if (ret == 0) {
4939
                /* fragOffset is non-zero when sending fragments. On the last
4940
                 * fragment, fragOffset is zero again, and the state can be
4941
                 * advanced. */
4942
0
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
4943
0
                    if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE ||
4944
0
                        ssl->options.acceptState == SERVER_HELLO_SENT ||
4945
0
                        ssl->options.acceptState == CERT_SENT ||
4946
0
                        ssl->options.acceptState == CERT_STATUS_SENT ||
4947
0
                        ssl->options.acceptState == KEY_EXCHANGE_SENT ||
4948
0
                        ssl->options.acceptState == CERT_REQ_SENT ||
4949
0
                        ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE ||
4950
0
                        ssl->options.acceptState == TICKET_SENT ||
4951
0
                        ssl->options.acceptState == CHANGE_CIPHER_SENT) {
4952
0
                        ssl->options.acceptState++;
4953
0
                        WOLFSSL_MSG("accept state: Advanced from last "
4954
0
                                    "buffered fragment send");
4955
0
                    #ifdef WOLFSSL_ASYNC_IO
4956
                        /* Cleanup async */
4957
0
                        FreeAsyncCtx(ssl, 0);
4958
0
                    #endif
4959
0
                    }
4960
0
                }
4961
0
                else {
4962
0
                    WOLFSSL_MSG("accept state: "
4963
0
                                "Not advanced, more fragments to send");
4964
0
                }
4965
0
            }
4966
0
            else {
4967
0
                ssl->error = ret;
4968
0
                WOLFSSL_ERROR(ssl->error);
4969
0
                return WOLFSSL_FATAL_ERROR;
4970
0
            }
4971
#ifdef WOLFSSL_DTLS13
4972
            if (ssl->options.dtls)
4973
                ssl->dtls13SendingAckOrRtx = 0;
4974
#endif /* WOLFSSL_DTLS13 */
4975
0
        }
4976
4977
0
        ret = RetrySendAlert(ssl);
4978
0
        if (ret != 0) {
4979
0
            ssl->error = ret;
4980
0
            WOLFSSL_ERROR(ssl->error);
4981
0
            return WOLFSSL_FATAL_ERROR;
4982
0
        }
4983
4984
0
        switch (ssl->options.acceptState) {
4985
4986
0
        case ACCEPT_BEGIN :
4987
#ifdef HAVE_SECURE_RENEGOTIATION
4988
        case ACCEPT_BEGIN_RENEG:
4989
#endif
4990
            /* get response */
4991
0
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
4992
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
4993
0
                    WOLFSSL_ERROR(ssl->error);
4994
0
                    return WOLFSSL_FATAL_ERROR;
4995
0
                }
4996
0
#ifdef WOLFSSL_TLS13
4997
0
            ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
4998
0
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
4999
0
            FALL_THROUGH;
5000
5001
0
        case ACCEPT_CLIENT_HELLO_DONE :
5002
0
            if (ssl->options.tls1_3) {
5003
0
                return wolfSSL_accept_TLSv13(ssl);
5004
0
            }
5005
0
#endif
5006
5007
0
            ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
5008
0
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
5009
0
            FALL_THROUGH;
5010
5011
0
        case ACCEPT_FIRST_REPLY_DONE :
5012
0
            if (ssl->options.returnOnGoodCh) {
5013
                /* Higher level in stack wants us to return. Simulate a
5014
                 * WANT_WRITE to accomplish this. */
5015
0
                ssl->error = WANT_WRITE;
5016
0
                return WOLFSSL_FATAL_ERROR;
5017
0
            }
5018
0
            if ( (ssl->error = SendServerHello(ssl)) != 0) {
5019
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5020
0
                WOLFSSL_ERROR(ssl->error);
5021
0
                return WOLFSSL_FATAL_ERROR;
5022
0
            }
5023
0
            ssl->options.acceptState = SERVER_HELLO_SENT;
5024
0
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
5025
0
            FALL_THROUGH;
5026
5027
0
        case SERVER_HELLO_SENT :
5028
0
        #ifdef WOLFSSL_TLS13
5029
0
            if (ssl->options.tls1_3) {
5030
0
                return wolfSSL_accept_TLSv13(ssl);
5031
0
            }
5032
0
        #endif
5033
0
            #ifndef NO_CERTS
5034
0
                if (!ssl->options.resuming)
5035
0
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
5036
0
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5037
0
                        WOLFSSL_ERROR(ssl->error);
5038
0
                        return WOLFSSL_FATAL_ERROR;
5039
0
                    }
5040
0
            #endif
5041
0
            ssl->options.acceptState = CERT_SENT;
5042
0
            WOLFSSL_MSG("accept state CERT_SENT");
5043
0
            FALL_THROUGH;
5044
5045
0
        case CERT_SENT :
5046
0
            #ifndef NO_CERTS
5047
0
            if (!ssl->options.resuming)
5048
0
                if ( (ssl->error = SendCertificateStatus(ssl)) != 0) {
5049
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5050
0
                    WOLFSSL_ERROR(ssl->error);
5051
0
                    return WOLFSSL_FATAL_ERROR;
5052
0
                }
5053
0
            #endif
5054
0
            ssl->options.acceptState = CERT_STATUS_SENT;
5055
0
            WOLFSSL_MSG("accept state CERT_STATUS_SENT");
5056
0
            FALL_THROUGH;
5057
5058
0
        case CERT_STATUS_SENT :
5059
0
        #ifdef WOLFSSL_TLS13
5060
0
            if (ssl->options.tls1_3) {
5061
0
                return wolfSSL_accept_TLSv13(ssl);
5062
0
            }
5063
0
        #endif
5064
0
            if (!ssl->options.resuming)
5065
0
                if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
5066
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5067
0
                    WOLFSSL_ERROR(ssl->error);
5068
0
                    return WOLFSSL_FATAL_ERROR;
5069
0
                }
5070
0
            ssl->options.acceptState = KEY_EXCHANGE_SENT;
5071
0
            WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
5072
0
            FALL_THROUGH;
5073
5074
0
        case KEY_EXCHANGE_SENT :
5075
0
            #ifndef NO_CERTS
5076
0
                if (!ssl->options.resuming) {
5077
0
                    if (ssl->options.verifyPeer) {
5078
0
                        if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
5079
0
                            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5080
0
                            WOLFSSL_ERROR(ssl->error);
5081
0
                            return WOLFSSL_FATAL_ERROR;
5082
0
                        }
5083
0
                    }
5084
0
                    else {
5085
                        /* SERVER: Peer auth good if not verifying client. */
5086
0
                        ssl->options.peerAuthGood = 1;
5087
0
                    }
5088
0
                }
5089
0
            #endif
5090
0
            ssl->options.acceptState = CERT_REQ_SENT;
5091
0
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
5092
0
            FALL_THROUGH;
5093
5094
0
        case CERT_REQ_SENT :
5095
0
            if (!ssl->options.resuming)
5096
0
                if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
5097
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5098
0
                    WOLFSSL_ERROR(ssl->error);
5099
0
                    return WOLFSSL_FATAL_ERROR;
5100
0
                }
5101
0
            ssl->options.acceptState = SERVER_HELLO_DONE;
5102
0
            WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
5103
0
            FALL_THROUGH;
5104
5105
0
        case SERVER_HELLO_DONE :
5106
0
            if (!ssl->options.resuming) {
5107
0
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
5108
0
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
5109
0
                        WOLFSSL_ERROR(ssl->error);
5110
0
                        return WOLFSSL_FATAL_ERROR;
5111
0
                    }
5112
0
            }
5113
0
            ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
5114
0
            WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
5115
0
            FALL_THROUGH;
5116
5117
0
        case ACCEPT_SECOND_REPLY_DONE :
5118
0
        #ifndef NO_CERTS
5119
            /* SERVER: When not resuming and verifying peer but no certificate
5120
             * received and not failing when not received then peer auth good.
5121
             */
5122
0
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
5123
0
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
5124
0
                ssl->options.peerAuthGood = 1;
5125
0
            }
5126
0
        #endif /* !NO_CERTS  */
5127
        #ifdef WOLFSSL_NO_CLIENT_AUTH
5128
            if (!ssl->options.resuming) {
5129
                ssl->options.peerAuthGood = 1;
5130
            }
5131
        #endif
5132
5133
#ifdef HAVE_SESSION_TICKET
5134
            if (ssl->options.createTicket && !ssl->options.noTicketTls12) {
5135
                if ( (ssl->error = SendTicket(ssl)) != 0) {
5136
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5137
                    WOLFSSL_MSG("Thought we need ticket but failed");
5138
                    WOLFSSL_ERROR(ssl->error);
5139
                    return WOLFSSL_FATAL_ERROR;
5140
                }
5141
            }
5142
#endif /* HAVE_SESSION_TICKET */
5143
0
            ssl->options.acceptState = TICKET_SENT;
5144
0
            WOLFSSL_MSG("accept state  TICKET_SENT");
5145
0
            FALL_THROUGH;
5146
5147
0
        case TICKET_SENT:
5148
            /* SERVER: Fail-safe for CLient Authentication. */
5149
0
            if (!ssl->options.peerAuthGood) {
5150
0
                WOLFSSL_MSG("Client authentication did not happen");
5151
0
                return WOLFSSL_FATAL_ERROR;
5152
0
            }
5153
5154
0
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
5155
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5156
0
                WOLFSSL_ERROR(ssl->error);
5157
0
                return WOLFSSL_FATAL_ERROR;
5158
0
            }
5159
0
            ssl->options.acceptState = CHANGE_CIPHER_SENT;
5160
0
            WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
5161
0
            FALL_THROUGH;
5162
5163
0
        case CHANGE_CIPHER_SENT :
5164
0
            if ( (ssl->error = SendFinished(ssl)) != 0) {
5165
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5166
0
                WOLFSSL_ERROR(ssl->error);
5167
0
                return WOLFSSL_FATAL_ERROR;
5168
0
            }
5169
5170
0
            ssl->options.acceptState = ACCEPT_FINISHED_DONE;
5171
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
5172
0
            FALL_THROUGH;
5173
5174
0
        case ACCEPT_FINISHED_DONE :
5175
0
            if (ssl->options.resuming) {
5176
0
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
5177
0
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
5178
0
                        WOLFSSL_ERROR(ssl->error);
5179
0
                        return WOLFSSL_FATAL_ERROR;
5180
0
                    }
5181
0
                }
5182
0
            }
5183
0
            ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
5184
0
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
5185
0
            FALL_THROUGH;
5186
5187
0
        case ACCEPT_THIRD_REPLY_DONE :
5188
0
#ifndef NO_HANDSHAKE_DONE_CB
5189
0
            if (ssl->hsDoneCb) {
5190
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
5191
0
                if (cbret < 0) {
5192
0
                    ssl->error = cbret;
5193
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
5194
0
                    return WOLFSSL_FATAL_ERROR;
5195
0
                }
5196
0
            }
5197
0
#endif /* NO_HANDSHAKE_DONE_CB */
5198
5199
0
            if (!ssl->options.dtls) {
5200
0
                if (!ssl->options.keepResources) {
5201
0
                    FreeHandshakeResources(ssl);
5202
0
                }
5203
0
            }
5204
#ifdef WOLFSSL_DTLS
5205
            else {
5206
                ssl->options.dtlsHsRetain = 1;
5207
            }
5208
#endif /* WOLFSSL_DTLS */
5209
5210
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
5211
            /* This may be necessary in async so that we don't try to
5212
             * renegotiate again */
5213
            if (ssl->secure_renegotiation &&
5214
                    ssl->secure_renegotiation->startScr) {
5215
                ssl->secure_renegotiation->startScr = 0;
5216
            }
5217
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
5218
0
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
5219
            /* Free the remaining async context if not using it for crypto */
5220
0
            FreeAsyncCtx(ssl, 1);
5221
0
#endif
5222
5223
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
5224
            if (ssl->dtls_export) {
5225
                if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
5226
                    WOLFSSL_MSG("Export DTLS session error");
5227
                    WOLFSSL_ERROR(ssl->error);
5228
                    return WOLFSSL_FATAL_ERROR;
5229
                }
5230
            }
5231
#endif
5232
0
            ssl->error = 0; /* clear the error */
5233
5234
0
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
5235
0
            return WOLFSSL_SUCCESS;
5236
5237
0
        default:
5238
0
            WOLFSSL_MSG("Unknown accept state ERROR");
5239
0
            return WOLFSSL_FATAL_ERROR;
5240
0
        }
5241
0
#endif /* !WOLFSSL_NO_TLS12 */
5242
0
    }
5243
5244
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
5245
/* end server only parts */
5246
5247
5248
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
5249
struct chGoodDisableReadCbCtx {
5250
    ClientHelloGoodCb userCb;
5251
    void*             userCtx;
5252
};
5253
5254
static int chGoodDisableReadCB(WOLFSSL* ssl, void* ctx)
5255
{
5256
    struct chGoodDisableReadCbCtx* cb = (struct chGoodDisableReadCbCtx*)ctx;
5257
    int ret = 0;
5258
    if (cb->userCb != NULL)
5259
        ret = cb->userCb(ssl, cb->userCtx);
5260
    if (ret >= 0)
5261
        wolfSSL_SSLDisableRead(ssl);
5262
    return ret;
5263
}
5264
5265
/**
5266
 * Statelessly listen for a connection
5267
 * @param ssl The ssl object to use for listening to connections
5268
 * @return WOLFSSL_SUCCESS - ClientHello containing a valid cookie was received
5269
 *                           The connection can be continued with wolfSSL_accept
5270
 *         WOLFSSL_FAILURE - The I/O layer returned WANT_READ. This is either
5271
 *                           because there is no data to read and we are using
5272
 *                           non-blocking sockets or we sent a cookie request
5273
 *                           and we are waiting for a reply. The user should
5274
 *                           call wolfDTLS_accept_stateless again after data
5275
 *                           becomes available in the I/O layer.
5276
 *         WOLFSSL_FATAL_ERROR - A fatal error occurred. The ssl object should
5277
 *                           be free'd and allocated again to continue.
5278
 */
5279
int wolfDTLS_accept_stateless(WOLFSSL* ssl)
5280
{
5281
    byte disableRead;
5282
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
5283
    struct chGoodDisableReadCbCtx cb;
5284
5285
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
5286
5287
    if (ssl == NULL)
5288
        return WOLFSSL_FATAL_ERROR;
5289
5290
    /* Save this to restore it later */
5291
    disableRead = (byte)ssl->options.disableRead;
5292
    cb.userCb = ssl->chGoodCb;
5293
    cb.userCtx = ssl->chGoodCtx;
5294
5295
    /* Register our own callback so that we can disable reading */
5296
    if (wolfDTLS_SetChGoodCb(ssl, chGoodDisableReadCB, &cb) != WOLFSSL_SUCCESS)
5297
        return WOLFSSL_FATAL_ERROR;
5298
5299
    ssl->options.returnOnGoodCh = 1;
5300
    ret = wolfSSL_accept(ssl);
5301
    ssl->options.returnOnGoodCh = 0;
5302
    /* restore user options */
5303
    ssl->options.disableRead = disableRead;
5304
    (void)wolfDTLS_SetChGoodCb(ssl, cb.userCb, cb.userCtx);
5305
    if (ret == WOLFSSL_SUCCESS) {
5306
        WOLFSSL_MSG("should not happen. maybe the user called "
5307
                    "wolfDTLS_accept_stateless instead of wolfSSL_accept");
5308
    }
5309
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_READ) ||
5310
             ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
5311
        ssl->error = 0;
5312
        if (ssl->options.dtlsStateful)
5313
            ret = WOLFSSL_SUCCESS;
5314
        else
5315
            ret = WOLFSSL_FAILURE;
5316
    }
5317
    else {
5318
        ret = WOLFSSL_FATAL_ERROR;
5319
    }
5320
    return ret;
5321
}
5322
5323
/* WC_NO_INLINE: wolfDTLS_accept_stateless passes the address of a stack-local
5324
 * context here; the restore call before return clears it again. Preventing
5325
 * inlining hides that cross-frame assignment from GCC's -Wdangling-pointer
5326
 * analysis, which otherwise flags a false positive on GCC 14+. */
5327
WC_NO_INLINE
5328
int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx)
5329
{
5330
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
5331
5332
    if (ssl == NULL)
5333
        return BAD_FUNC_ARG;
5334
5335
    ssl->chGoodCb  = cb;
5336
    ssl->chGoodCtx = user_ctx;
5337
5338
    return WOLFSSL_SUCCESS;
5339
}
5340
#endif
5341
5342
#ifndef NO_HANDSHAKE_DONE_CB
5343
5344
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
5345
0
{
5346
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
5347
5348
0
    if (ssl == NULL)
5349
0
        return BAD_FUNC_ARG;
5350
5351
0
    ssl->hsDoneCb  = cb;
5352
0
    ssl->hsDoneCtx = user_ctx;
5353
5354
0
    return WOLFSSL_SUCCESS;
5355
0
}
5356
5357
#endif /* NO_HANDSHAKE_DONE_CB */
5358
5359
WOLFSSL_ABI
5360
int wolfSSL_Cleanup(void)
5361
0
{
5362
0
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
5363
0
    int release = 0;
5364
0
#if !defined(NO_SESSION_CACHE)
5365
0
    int i;
5366
0
    int j;
5367
0
#endif
5368
5369
0
    WOLFSSL_ENTER("wolfSSL_Cleanup");
5370
5371
#ifndef WOLFSSL_MUTEX_INITIALIZER
5372
    if (inits_count_mutex_valid == 1) {
5373
#endif
5374
0
        if (wc_LockMutex(&inits_count_mutex) != 0) {
5375
0
            WOLFSSL_MSG("Bad Lock Mutex count");
5376
0
            return BAD_MUTEX_E;
5377
0
        }
5378
#ifndef WOLFSSL_MUTEX_INITIALIZER
5379
    }
5380
#endif
5381
5382
0
    if (initRefCount > 0) {
5383
0
        initRefCount = initRefCount - 1;
5384
0
        if (initRefCount == 0)
5385
0
            release = 1;
5386
0
    }
5387
5388
#ifndef WOLFSSL_MUTEX_INITIALIZER
5389
    if (inits_count_mutex_valid == 1) {
5390
#endif
5391
0
        wc_UnLockMutex(&inits_count_mutex);
5392
#ifndef WOLFSSL_MUTEX_INITIALIZER
5393
    }
5394
#endif
5395
5396
0
    if (!release)
5397
0
        return ret;
5398
5399
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5400
    wolfSSL_crypto_policy_disable();
5401
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5402
5403
#ifdef OPENSSL_EXTRA
5404
    wolfSSL_BN_free_one();
5405
#endif
5406
5407
0
#ifndef NO_SESSION_CACHE
5408
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
5409
    for (i = 0; i < SESSION_ROWS; ++i) {
5410
        if ((SessionCache[i].lock_valid == 1) &&
5411
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
5412
            if (ret == WOLFSSL_SUCCESS)
5413
                ret = BAD_MUTEX_E;
5414
        }
5415
        SessionCache[i].lock_valid = 0;
5416
    }
5417
    #else
5418
0
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
5419
0
        if (ret == WOLFSSL_SUCCESS)
5420
0
            ret = BAD_MUTEX_E;
5421
0
    }
5422
0
    session_lock_valid = 0;
5423
0
    #endif
5424
0
    for (i = 0; i < SESSION_ROWS; i++) {
5425
0
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
5426
    #ifdef SESSION_CACHE_DYNAMIC_MEM
5427
            if (SessionCache[i].Sessions[j]) {
5428
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
5429
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
5430
                      DYNAMIC_TYPE_SESSION);
5431
                SessionCache[i].Sessions[j] = NULL;
5432
            }
5433
    #else
5434
0
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
5435
0
    #endif
5436
0
        }
5437
0
    }
5438
0
    #ifndef NO_CLIENT_CACHE
5439
    #ifndef WOLFSSL_MUTEX_INITIALIZER
5440
    if ((clisession_mutex_valid == 1) &&
5441
        (wc_FreeMutex(&clisession_mutex) != 0)) {
5442
        if (ret == WOLFSSL_SUCCESS)
5443
            ret = BAD_MUTEX_E;
5444
    }
5445
    clisession_mutex_valid = 0;
5446
    #endif
5447
0
    #endif
5448
0
#endif /* !NO_SESSION_CACHE */
5449
5450
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
5451
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5452
    if ((inits_count_mutex_valid == 1) &&
5453
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
5454
        if (ret == WOLFSSL_SUCCESS)
5455
            ret = BAD_MUTEX_E;
5456
    }
5457
    inits_count_mutex_valid = 0;
5458
#endif
5459
5460
#ifdef OPENSSL_EXTRA
5461
    wolfSSL_RAND_Cleanup();
5462
#endif
5463
5464
0
    if (wolfCrypt_Cleanup() != 0) {
5465
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
5466
0
        if (ret == WOLFSSL_SUCCESS)
5467
0
            ret = WC_CLEANUP_E;
5468
0
    }
5469
5470
#if FIPS_VERSION_GE(5,1)
5471
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
5472
        if (ret == WOLFSSL_SUCCESS)
5473
            ret = WC_CLEANUP_E;
5474
    }
5475
#endif
5476
5477
0
#ifdef HAVE_GLOBAL_RNG
5478
#ifndef WOLFSSL_MUTEX_INITIALIZER
5479
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
5480
        if (ret == WOLFSSL_SUCCESS)
5481
            ret = BAD_MUTEX_E;
5482
    }
5483
    globalRNGMutex_valid = 0;
5484
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
5485
5486
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
5487
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
5488
    gDrbgDefCtx = NULL;
5489
    #endif
5490
0
#endif
5491
5492
#ifdef HAVE_EX_DATA_CRYPTO
5493
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
5494
    crypto_ex_cb_ctx_session = NULL;
5495
#endif
5496
5497
#ifdef WOLFSSL_MEM_FAIL_COUNT
5498
    wc_MemFailCount_Free();
5499
#endif
5500
5501
0
    return ret;
5502
0
}
5503
5504
/* Returns 1 if name is a syntactically valid DNS FQDN per RFC 952/1123.
5505
 *
5506
 * Rules enforced:
5507
 *   - Total effective length (excluding optional trailing dot) in [1, 253]
5508
 *   - Each label is 1-63 octets of [a-zA-Z0-9-], with _ allowed in all but
5509
 *     the last label.
5510
 *   - No label starts or ends with '-'
5511
 *   - At least two labels (single-label names are not "fully qualified")
5512
 *   - Final label (TLD) contains at least one letter (rejects all-numeric
5513
 *     strings that could be confused with IPv4 literals, and matches the
5514
 *     ICANN constraint that TLDs are alphabetic)
5515
 *   - Optional trailing dot is accepted (absolute FQDN form)
5516
 *   - Internationalized names are valid in their ACE/punycode (xn--) form
5517
 */
5518
int wolfssl_local_IsValidFQDN(const char* name, word32 nameSz)
5519
0
{
5520
0
    word32 i;
5521
0
    int labelLen = 0;
5522
0
    int labelCount = 0;
5523
0
    int curLabelHasAlpha = 0;
5524
0
    int curLabelHasUnderscore = 0;
5525
5526
0
    if (name == NULL || nameSz == 0)
5527
0
        return 0;
5528
5529
    /* Strip a single optional trailing dot before measuring.  "example.com."
5530
     * is the absolute form of the same FQDN.
5531
     */
5532
0
    if (name[nameSz - 1] == '.')
5533
0
        --nameSz;
5534
5535
0
    if (nameSz < 1 || nameSz > 253)
5536
0
        return 0;
5537
5538
0
    for (i = 0; i < nameSz; i++) {
5539
0
        byte c = (byte)name[i];
5540
5541
0
        if (c == '.') {
5542
0
            if (labelLen == 0 || name[i - 1] == '-')
5543
0
                return 0;
5544
0
            ++labelCount;
5545
0
            labelLen = 0;
5546
0
            curLabelHasAlpha = 0;
5547
0
            curLabelHasUnderscore = 0;
5548
0
            continue;
5549
0
        }
5550
5551
0
        if (++labelLen > 63)
5552
0
            return 0;
5553
5554
0
        if (c == '-') {
5555
0
            if (labelLen == 1)
5556
0
                return 0;
5557
0
        }
5558
0
        else if (((c | 0x20) >= 'a') && ((c | 0x20) <= 'z')) {
5559
0
            curLabelHasAlpha = 1;
5560
0
        }
5561
0
        else if (c == '_') {
5562
0
            curLabelHasUnderscore = 1;
5563
0
        }
5564
0
        else if ((c < '0') || (c > '9')) {
5565
0
            return 0;
5566
0
        }
5567
0
    }
5568
5569
    /* Final label (no trailing dot in the effective range to close it) */
5570
0
    if ((labelLen == 0) || (name[nameSz - 1] == '-') || curLabelHasUnderscore)
5571
0
        return 0;
5572
0
    ++labelCount;
5573
5574
0
    return ((labelCount > 1) && curLabelHasAlpha);
5575
0
}
5576
5577
/* call before SSL_connect, if verifying will add name check to
5578
   date check and signature check */
5579
WOLFSSL_ABI
5580
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
5581
0
{
5582
0
    size_t dn_len;
5583
5584
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
5585
5586
0
    if (ssl == NULL || dn == NULL) {
5587
0
        WOLFSSL_MSG("Bad function argument: NULL");
5588
0
        return WOLFSSL_FAILURE;
5589
0
    }
5590
5591
0
    dn_len = XSTRLEN(dn);
5592
5593
0
    if ((! wolfssl_local_IsValidFQDN(dn, (word32)dn_len)) &&
5594
0
        (XSTRCMP(dn, "localhost") != 0))
5595
0
    {
5596
0
        WOLFSSL_MSG("Bad function argument: fails wolfssl_local_IsValidFQDN");
5597
0
        return WOLFSSL_FAILURE;
5598
0
    }
5599
5600
0
    if (ssl->buffers.domainName.buffer)
5601
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5602
5603
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
5604
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
5605
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5606
5607
0
    if (ssl->buffers.domainName.buffer) {
5608
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
5609
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
5610
0
        domainName[ssl->buffers.domainName.length] = '\0';
5611
0
        return WOLFSSL_SUCCESS;
5612
0
    }
5613
0
    else {
5614
0
        ssl->error = MEMORY_ERROR;
5615
0
        return WOLFSSL_FAILURE;
5616
0
    }
5617
0
}
5618
5619
/* call before SSL_connect, if verifying will add IP SAN check to
5620
   date check and signature check */
5621
WOLFSSL_ABI
5622
int wolfSSL_check_ip_address(WOLFSSL* ssl, const char* ipaddr)
5623
0
{
5624
0
    WOLFSSL_ENTER("wolfSSL_check_ip_address");
5625
5626
0
    if (ssl == NULL || ipaddr == NULL) {
5627
0
        WOLFSSL_MSG("Bad function argument: NULL");
5628
0
        return WOLFSSL_FAILURE;
5629
0
    }
5630
5631
0
    if (ssl->buffers.ipasc.buffer != NULL) {
5632
0
        XFREE(ssl->buffers.ipasc.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5633
0
        ssl->buffers.ipasc.buffer = NULL;
5634
0
        ssl->buffers.ipasc.length = 0;
5635
0
    }
5636
5637
0
    ssl->buffers.ipasc.length = (word32)XSTRLEN(ipaddr);
5638
0
    ssl->buffers.ipasc.buffer = (byte*)XMALLOC(ssl->buffers.ipasc.length + 1,
5639
0
                                               ssl->heap, DYNAMIC_TYPE_DOMAIN);
5640
0
    if (ssl->buffers.ipasc.buffer == NULL) {
5641
0
        ssl->error = MEMORY_ERROR;
5642
0
        return WOLFSSL_FAILURE;
5643
0
    }
5644
5645
0
    XMEMCPY(ssl->buffers.ipasc.buffer, ipaddr, ssl->buffers.ipasc.length);
5646
0
    ssl->buffers.ipasc.buffer[ssl->buffers.ipasc.length] = '\0';
5647
5648
#ifdef OPENSSL_EXTRA
5649
    if (ssl->param == NULL) {
5650
        return WOLFSSL_FAILURE;
5651
    }
5652
    if (wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(ssl->param, ipaddr) !=
5653
            WOLFSSL_SUCCESS) {
5654
        return WOLFSSL_FAILURE;
5655
    }
5656
#endif
5657
5658
0
    return WOLFSSL_SUCCESS;
5659
0
}
5660
5661
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
5662
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
5663
    if (ssl == NULL) {
5664
        return NULL;
5665
    }
5666
5667
    if (ssl->buffers.domainName.buffer)
5668
        return (const char *)ssl->buffers.domainName.buffer;
5669
    else if (ssl->session && ssl->session->peer)
5670
        return ssl->session->peer->subjectCN;
5671
#ifdef KEEP_PEER_CERT
5672
    else if (ssl->peerCert.subjectCN[0])
5673
        return ssl->peerCert.subjectCN;
5674
#endif
5675
    else {
5676
        ssl->error = NO_PEER_CERT;
5677
        return NULL;
5678
    }
5679
}
5680
5681
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
5682
5683
/* turn on wolfSSL zlib compression
5684
   returns WOLFSSL_SUCCESS for success, else error (not built in)
5685
*/
5686
int wolfSSL_set_compression(WOLFSSL* ssl)
5687
0
{
5688
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
5689
0
    (void)ssl;
5690
#ifdef HAVE_LIBZ
5691
    ssl->options.usingCompression = 1;
5692
    return WOLFSSL_SUCCESS;
5693
#else
5694
0
    return NOT_COMPILED_IN;
5695
0
#endif
5696
0
}
5697
5698
5699
#ifndef USE_WINDOWS_API
5700
    #if !defined(NO_WRITEV) && !defined(NO_TLS)
5701
5702
        /* simulate writev semantics, doesn't actually do block at a time though
5703
           because of SSL_write behavior and because front adds may be small */
5704
        int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt)
5705
0
        {
5706
        #ifdef WOLFSSL_SMALL_STACK
5707
            byte   staticBuffer[1]; /* force heap usage */
5708
        #else
5709
0
            byte   staticBuffer[FILE_BUFFER_SIZE];
5710
0
        #endif
5711
0
            byte* myBuffer  = staticBuffer;
5712
0
            int   dynamic   = 0;
5713
0
            size_t sending   = 0;
5714
0
            size_t idx       = 0;
5715
0
            int   i;
5716
0
            int   ret;
5717
5718
0
            WOLFSSL_ENTER("wolfSSL_writev");
5719
5720
0
            for (i = 0; i < iovcnt; i++)
5721
0
                if (! WC_SAFE_SUM_UNSIGNED(size_t, sending, iov[i].iov_len,
5722
0
                                           sending))
5723
0
                    return BUFFER_E;
5724
5725
0
            if (sending > sizeof(staticBuffer)) {
5726
0
                myBuffer = (byte*)XMALLOC(sending, ssl->heap,
5727
0
                                          DYNAMIC_TYPE_WRITEV);
5728
0
                if (!myBuffer)
5729
0
                    return MEMORY_ERROR;
5730
5731
0
                dynamic = 1;
5732
0
            }
5733
5734
0
            for (i = 0; i < iovcnt; i++) {
5735
0
                XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
5736
0
                idx += (int)iov[i].iov_len;
5737
0
            }
5738
5739
           /* myBuffer may not be initialized fully, but the span up to the
5740
            * sending length will be.
5741
            */
5742
0
            PRAGMA_GCC_DIAG_PUSH
5743
0
            PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
5744
0
            ret = wolfSSL_write_internal(ssl, myBuffer, sending);
5745
0
            PRAGMA_GCC_DIAG_POP
5746
5747
0
            if (dynamic)
5748
0
                XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
5749
5750
0
            return ret;
5751
0
        }
5752
    #endif
5753
#endif
5754
5755
5756
#ifdef WOLFSSL_CALLBACKS
5757
5758
    typedef struct itimerval Itimerval;
5759
5760
    /* don't keep calling simple functions while setting up timer and signals
5761
       if no inlining these are the next best */
5762
5763
    #define AddTimes(a, b, c)                       \
5764
        do {                                        \
5765
            (c).tv_sec  = (a).tv_sec + (b).tv_sec;  \
5766
            (c).tv_usec = (a).tv_usec + (b).tv_usec;\
5767
            if ((c).tv_usec >=  1000000) {          \
5768
                (c).tv_sec++;                       \
5769
                (c).tv_usec -= 1000000;             \
5770
            }                                       \
5771
        } while (0)
5772
5773
5774
    #define SubtractTimes(a, b, c)                  \
5775
        do {                                        \
5776
            (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
5777
            (c).tv_usec = (a).tv_usec - (b).tv_usec;\
5778
            if ((c).tv_usec < 0) {                  \
5779
                (c).tv_sec--;                       \
5780
                (c).tv_usec += 1000000;             \
5781
            }                                       \
5782
        } while (0)
5783
5784
    #define CmpTimes(a, b, cmp)                     \
5785
        (((a).tv_sec  ==  (b).tv_sec) ?             \
5786
            ((a).tv_usec cmp (b).tv_usec) :         \
5787
            ((a).tv_sec  cmp (b).tv_sec))           \
5788
5789
5790
    /* do nothing handler */
5791
    static void myHandler(int signo)
5792
    {
5793
        (void)signo;
5794
        return;
5795
    }
5796
5797
5798
    static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
5799
                                 TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5800
    {
5801
        int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
5802
        int       oldTimerOn = 0;   /* was timer already on */
5803
        WOLFSSL_TIMEVAL startTime;
5804
        WOLFSSL_TIMEVAL endTime;
5805
        WOLFSSL_TIMEVAL totalTime;
5806
        Itimerval myTimeout;
5807
        Itimerval oldTimeout; /* if old timer adjust from total time to reset */
5808
        struct sigaction act, oact;
5809
5810
        #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; }
5811
5812
        if (hsCb) {
5813
            ssl->hsInfoOn = 1;
5814
            InitHandShakeInfo(&ssl->handShakeInfo, ssl);
5815
        }
5816
        if (toCb) {
5817
            ssl->toInfoOn = 1;
5818
            InitTimeoutInfo(&ssl->timeoutInfo);
5819
5820
            if (gettimeofday(&startTime, 0) < 0)
5821
                ERR_OUT(GETTIME_ERROR);
5822
5823
            /* use setitimer to simulate getitimer, init 0 myTimeout */
5824
            myTimeout.it_interval.tv_sec  = 0;
5825
            myTimeout.it_interval.tv_usec = 0;
5826
            myTimeout.it_value.tv_sec     = 0;
5827
            myTimeout.it_value.tv_usec    = 0;
5828
            if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0)
5829
                ERR_OUT(SETITIMER_ERROR);
5830
5831
            if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) {
5832
                oldTimerOn = 1;
5833
5834
                /* is old timer going to expire before ours */
5835
                if (CmpTimes(oldTimeout.it_value, timeout, <)) {
5836
                    timeout.tv_sec  = oldTimeout.it_value.tv_sec;
5837
                    timeout.tv_usec = oldTimeout.it_value.tv_usec;
5838
                }
5839
            }
5840
            myTimeout.it_value.tv_sec  = timeout.tv_sec;
5841
            myTimeout.it_value.tv_usec = timeout.tv_usec;
5842
5843
            /* set up signal handler, don't restart socket send/recv */
5844
            act.sa_handler = myHandler;
5845
            sigemptyset(&act.sa_mask);
5846
            act.sa_flags = 0;
5847
#ifdef SA_INTERRUPT
5848
            act.sa_flags |= SA_INTERRUPT;
5849
#endif
5850
            if (sigaction(SIGALRM, &act, &oact) < 0)
5851
                ERR_OUT(SIGACT_ERROR);
5852
5853
            if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0)
5854
                ERR_OUT(SETITIMER_ERROR);
5855
        }
5856
5857
        /* do main work */
5858
#ifndef NO_WOLFSSL_CLIENT
5859
        if (ssl->options.side == WOLFSSL_CLIENT_END)
5860
            ret = wolfSSL_connect(ssl);
5861
#endif
5862
#ifndef NO_WOLFSSL_SERVER
5863
        if (ssl->options.side == WOLFSSL_SERVER_END)
5864
            ret = wolfSSL_accept(ssl);
5865
#endif
5866
5867
        /* do callbacks */
5868
        if (toCb) {
5869
            if (oldTimerOn) {
5870
                if (gettimeofday(&endTime, 0) < 0)
5871
                    ERR_OUT(SYSLIB_FAILED_E);
5872
                SubtractTimes(endTime, startTime, totalTime);
5873
                /* adjust old timer for elapsed time */
5874
                if (CmpTimes(totalTime, oldTimeout.it_value, <))
5875
                    SubtractTimes(oldTimeout.it_value, totalTime,
5876
                                  oldTimeout.it_value);
5877
                else {
5878
                    /* reset value to interval, may be off */
5879
                    oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec;
5880
                    oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec;
5881
                }
5882
                /* keep iter the same whether there or not */
5883
            }
5884
            /* restore old handler */
5885
            if (sigaction(SIGALRM, &oact, 0) < 0)
5886
                ret = SIGACT_ERROR;    /* more pressing error, stomp */
5887
            else
5888
                /* use old settings which may turn off (expired or not there) */
5889
                if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0)
5890
                    ret = SETITIMER_ERROR;
5891
5892
            /* if we had a timeout call callback */
5893
            if (ssl->timeoutInfo.timeoutName[0]) {
5894
                ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
5895
                ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
5896
                (toCb)(&ssl->timeoutInfo);
5897
            }
5898
            ssl->toInfoOn = 0;
5899
        }
5900
5901
        /* clean up buffers allocated by AddPacketInfo */
5902
        FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
5903
5904
        if (hsCb) {
5905
            FinishHandShakeInfo(&ssl->handShakeInfo);
5906
            (hsCb)(&ssl->handShakeInfo);
5907
            ssl->hsInfoOn = 0;
5908
        }
5909
        return ret;
5910
    }
5911
5912
5913
#ifndef NO_WOLFSSL_CLIENT
5914
5915
    int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
5916
                          TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5917
    {
5918
        WOLFSSL_ENTER("wolfSSL_connect_ex");
5919
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
5920
    }
5921
5922
#endif
5923
5924
5925
#ifndef NO_WOLFSSL_SERVER
5926
5927
    int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
5928
                         TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5929
    {
5930
        WOLFSSL_ENTER("wolfSSL_accept_ex");
5931
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
5932
    }
5933
5934
#endif
5935
5936
#endif /* WOLFSSL_CALLBACKS */
5937
5938
5939
#ifndef NO_PSK
5940
5941
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
5942
                                         wc_psk_client_callback cb)
5943
    {
5944
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
5945
5946
        if (ctx == NULL)
5947
            return;
5948
5949
        ctx->havePSK = 1;
5950
        ctx->client_psk_cb = cb;
5951
    }
5952
5953
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
5954
    {
5955
        byte haveRSA = 1;
5956
        int  keySz   = 0;
5957
5958
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
5959
5960
        if (ssl == NULL)
5961
            return;
5962
5963
        ssl->options.havePSK = 1;
5964
        ssl->options.client_psk_cb = cb;
5965
5966
        #ifdef NO_RSA
5967
            haveRSA = 0;
5968
        #endif
5969
        #ifndef NO_CERTS
5970
            keySz = ssl->buffers.keySz;
5971
        #endif
5972
        if (AllocateSuites(ssl) != 0)
5973
            return;
5974
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
5975
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
5976
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
5977
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
5978
    }
5979
5980
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
5981
    int wolfSSL_CTX_set_cert_with_extern_psk(WOLFSSL_CTX* ctx, int state)
5982
    {
5983
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_with_extern_psk");
5984
        if (ctx == NULL)
5985
            return WOLFSSL_FAILURE;
5986
        ctx->certWithExternPsk = (byte)(state != 0);
5987
        return WOLFSSL_SUCCESS;
5988
    }
5989
5990
    int wolfSSL_set_cert_with_extern_psk(WOLFSSL* ssl, int state)
5991
    {
5992
        WOLFSSL_ENTER("wolfSSL_set_cert_with_extern_psk");
5993
        if (ssl == NULL)
5994
            return WOLFSSL_FAILURE;
5995
        ssl->options.certWithExternPsk = (word16)(state != 0);
5996
        return WOLFSSL_SUCCESS;
5997
    }
5998
#endif
5999
6000
    #ifdef OPENSSL_EXTRA
6001
    /**
6002
     * set call back function for psk session use
6003
     * @param ssl  a pointer to WOLFSSL structure
6004
     * @param cb   a function pointer to wc_psk_use_session_cb
6005
     * @return none
6006
     */
6007
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
6008
                                                wc_psk_use_session_cb_func cb)
6009
    {
6010
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
6011
6012
        if (ssl != NULL) {
6013
            ssl->options.havePSK = 1;
6014
            ssl->options.session_psk_cb = cb;
6015
        }
6016
6017
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
6018
    }
6019
    #endif
6020
6021
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
6022
                                         wc_psk_server_callback cb)
6023
    {
6024
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
6025
        if (ctx == NULL)
6026
            return;
6027
        ctx->havePSK = 1;
6028
        ctx->server_psk_cb = cb;
6029
    }
6030
6031
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
6032
    {
6033
        byte haveRSA = 1;
6034
        int  keySz   = 0;
6035
6036
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
6037
        if (ssl == NULL)
6038
            return;
6039
6040
        ssl->options.havePSK = 1;
6041
        ssl->options.server_psk_cb = cb;
6042
6043
        #ifdef NO_RSA
6044
            haveRSA = 0;
6045
        #endif
6046
        #ifndef NO_CERTS
6047
            keySz = ssl->buffers.keySz;
6048
        #endif
6049
        if (AllocateSuites(ssl) != 0)
6050
            return;
6051
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
6052
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
6053
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
6054
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
6055
    }
6056
6057
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
6058
    {
6059
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
6060
6061
        if (ssl == NULL || ssl->arrays == NULL)
6062
            return NULL;
6063
6064
        return ssl->arrays->server_hint;
6065
    }
6066
6067
6068
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
6069
    {
6070
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
6071
6072
        if (ssl == NULL || ssl->arrays == NULL)
6073
            return NULL;
6074
6075
        return ssl->arrays->client_identity;
6076
    }
6077
6078
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
6079
    {
6080
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
6081
        if (hint == 0)
6082
            ctx->server_hint[0] = '\0';
6083
        else {
6084
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
6085
            #ifdef WOLFSSL_QT
6086
            ctx->havePSK=1;
6087
            #endif
6088
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
6089
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
6090
        }
6091
        return WOLFSSL_SUCCESS;
6092
    }
6093
6094
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
6095
    {
6096
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
6097
6098
        if (ssl == NULL || ssl->arrays == NULL)
6099
            return WOLFSSL_FAILURE;
6100
6101
        if (hint == 0)
6102
            ssl->arrays->server_hint[0] = 0;
6103
        else {
6104
            XSTRNCPY(ssl->arrays->server_hint, hint,
6105
                                            sizeof(ssl->arrays->server_hint)-1);
6106
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
6107
        }
6108
        return WOLFSSL_SUCCESS;
6109
    }
6110
6111
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
6112
    {
6113
        return ssl ? ssl->options.psk_ctx : NULL;
6114
    }
6115
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
6116
    {
6117
        return ctx ? ctx->psk_ctx : NULL;
6118
    }
6119
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
6120
    {
6121
        if (ssl == NULL)
6122
            return WOLFSSL_FAILURE;
6123
        ssl->options.psk_ctx = psk_ctx;
6124
        return WOLFSSL_SUCCESS;
6125
    }
6126
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
6127
    {
6128
        if (ctx == NULL)
6129
            return WOLFSSL_FAILURE;
6130
        ctx->psk_ctx = psk_ctx;
6131
        return WOLFSSL_SUCCESS;
6132
    }
6133
#endif /* NO_PSK */
6134
6135
6136
#ifdef HAVE_ANON
6137
6138
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
6139
    {
6140
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
6141
6142
        if (ctx == NULL)
6143
            return WOLFSSL_FAILURE;
6144
6145
        ctx->useAnon = 1;
6146
6147
        return WOLFSSL_SUCCESS;
6148
    }
6149
6150
#endif /* HAVE_ANON */
6151
6152
#ifdef OPENSSL_EXTRA
6153
6154
    int wolfSSL_add_all_algorithms(void)
6155
    {
6156
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
6157
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
6158
            return WOLFSSL_SUCCESS;
6159
        else
6160
            return WOLFSSL_FATAL_ERROR;
6161
    }
6162
6163
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
6164
    {
6165
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
6166
6167
        if  (wolfSSL_add_all_algorithms() ==
6168
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
6169
        {
6170
            return WOLFSSL_FATAL_ERROR;
6171
        }
6172
6173
        return  WOLFSSL_SUCCESS;
6174
    }
6175
6176
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
6177
    {
6178
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
6179
        /* This function is currently the same as
6180
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
6181
        the use of a wolfssl.cnf type configuration file and is only used for
6182
        OpenSSL compatibility. */
6183
6184
        if (wolfSSL_add_all_algorithms() ==
6185
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
6186
        {
6187
            return WOLFSSL_FATAL_ERROR;
6188
        }
6189
        return WOLFSSL_SUCCESS;
6190
    }
6191
6192
#endif
6193
6194
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
6195
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
6196
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
6197
    {
6198
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
6199
        if (mode)
6200
            ctx->quietShutdown = 1;
6201
    }
6202
6203
6204
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
6205
    {
6206
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
6207
        if (mode)
6208
            ssl->options.quietShutdown = 1;
6209
    }
6210
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
6211
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
6212
6213
#ifdef OPENSSL_EXTRA
6214
#ifndef NO_BIO
6215
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
6216
    {
6217
        WOLFSSL_ENTER("wolfSSL_set_bio");
6218
6219
        if (ssl == NULL) {
6220
            WOLFSSL_MSG("Bad argument, ssl was NULL");
6221
            return;
6222
        }
6223
6224
        /* free any existing WOLFSSL_BIOs in use but don't free those in
6225
         * a chain */
6226
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
6227
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
6228
                if (ssl->biowr != NULL && ssl->biowr->prev == NULL)
6229
                    wolfSSL_BIO_free(ssl->biowr);
6230
                ssl->biowr = NULL;
6231
            }
6232
            if (ssl->biord->prev == NULL)
6233
                wolfSSL_BIO_free(ssl->biord);
6234
            ssl->biord = NULL;
6235
        }
6236
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
6237
            if (ssl->biowr->prev == NULL)
6238
                wolfSSL_BIO_free(ssl->biowr);
6239
            ssl->biowr = NULL;
6240
        }
6241
6242
        /* set flag obviously */
6243
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
6244
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
6245
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
6246
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
6247
6248
        if (flags & WOLFSSL_BIO_FLAG_READ)
6249
            ssl->biord = rd;
6250
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
6251
            ssl->biowr = wr;
6252
6253
        /* set SSL to use BIO callbacks instead */
6254
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
6255
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
6256
        {
6257
            ssl->CBIORecv = SslBioReceive;
6258
        }
6259
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
6260
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
6261
        {
6262
            ssl->CBIOSend = SslBioSend;
6263
        }
6264
6265
        /* User programs should always retry reading from these BIOs */
6266
        if (rd) {
6267
            /* User writes to rd */
6268
            wolfSSL_BIO_set_retry_write(rd);
6269
        }
6270
        if (wr) {
6271
            /* User reads from wr */
6272
            wolfSSL_BIO_set_retry_read(wr);
6273
        }
6274
    }
6275
6276
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
6277
    {
6278
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
6279
    }
6280
6281
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
6282
    {
6283
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
6284
    }
6285
6286
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
6287
    {
6288
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
6289
    }
6290
6291
#endif /* !NO_BIO */
6292
#endif /* OPENSSL_EXTRA */
6293
6294
#ifdef WOLFSSL_CERT_SETUP_CB
6295
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
6296
    /* registers client cert callback, called during handshake if server
6297
       requests client auth but user has not loaded client cert/key */
6298
    void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb)
6299
    {
6300
        WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb");
6301
6302
        if (ctx != NULL) {
6303
            ctx->CBClientCert = cb;
6304
        }
6305
    }
6306
#endif
6307
6308
    void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx,
6309
        CertSetupCallback cb, void *arg)
6310
    {
6311
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb");
6312
        if (ctx == NULL)
6313
            return;
6314
6315
        ctx->certSetupCb = cb;
6316
        ctx->certSetupCbArg = arg;
6317
    }
6318
6319
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
6320
            const byte** suites, word16* suiteSz,
6321
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
6322
    {
6323
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
6324
6325
        if (suites != NULL)
6326
            *suites = NULL;
6327
        if (suiteSz != NULL)
6328
            *suiteSz = 0;
6329
        if (hashSigAlgo != NULL)
6330
            *hashSigAlgo = NULL;
6331
        if (hashSigAlgoSz != NULL)
6332
            *hashSigAlgoSz = 0;
6333
6334
        if (ssl != NULL && ssl->clSuites != NULL) {
6335
            if (suites != NULL && suiteSz != NULL) {
6336
                *suites = ssl->clSuites->suites;
6337
                *suiteSz = ssl->clSuites->suiteSz;
6338
            }
6339
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
6340
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
6341
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
6342
            }
6343
            return WOLFSSL_SUCCESS;
6344
        }
6345
        return WOLFSSL_FAILURE;
6346
    }
6347
6348
#ifndef NO_TLS
6349
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
6350
            byte second)
6351
    {
6352
        WOLFSSL_CIPHERSUITE_INFO info;
6353
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
6354
                CipherRequires(first, second, REQUIRES_RSA_SIG));
6355
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
6356
                /* Static ECC ciphers may require RSA for authentication */
6357
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
6358
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
6359
        info.eccStatic =
6360
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
6361
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
6362
        return info;
6363
    }
6364
#endif
6365
6366
    /**
6367
     * @param first First byte of the hash and signature algorithm
6368
     * @param second Second byte of the hash and signature algorithm
6369
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
6370
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
6371
     */
6372
    int wolfSSL_get_sigalg_info(byte first, byte second,
6373
            int* hashAlgo, int* sigAlgo)
6374
    {
6375
        byte input[2];
6376
        byte hashType;
6377
        byte sigType;
6378
6379
        if (hashAlgo == NULL || sigAlgo == NULL)
6380
            return BAD_FUNC_ARG;
6381
6382
        input[0] = first;
6383
        input[1] = second;
6384
        DecodeSigAlg(input, &hashType, &sigType);
6385
6386
        /* cast so that compiler reminds us of unimplemented values */
6387
        switch ((enum SignatureAlgorithm)sigType) {
6388
        case anonymous_sa_algo:
6389
            *sigAlgo = ANONk;
6390
            break;
6391
        case rsa_sa_algo:
6392
            *sigAlgo = RSAk;
6393
            break;
6394
        case dsa_sa_algo:
6395
            *sigAlgo = DSAk;
6396
            break;
6397
        case ecc_dsa_sa_algo:
6398
        case ecc_brainpool_sa_algo:
6399
            *sigAlgo = ECDSAk;
6400
            break;
6401
        case rsa_pss_sa_algo:
6402
            *sigAlgo = RSAPSSk;
6403
            break;
6404
        case ed25519_sa_algo:
6405
            *sigAlgo = ED25519k;
6406
            break;
6407
        case rsa_pss_pss_algo:
6408
            *sigAlgo = RSAPSSk;
6409
            break;
6410
        case ed448_sa_algo:
6411
            *sigAlgo = ED448k;
6412
            break;
6413
        case falcon_level1_sa_algo:
6414
            *sigAlgo = FALCON_LEVEL1k;
6415
            break;
6416
        case falcon_level5_sa_algo:
6417
            *sigAlgo = FALCON_LEVEL5k;
6418
            break;
6419
        case mldsa_44_sa_algo:
6420
            *sigAlgo = ML_DSA_44k;
6421
            break;
6422
        case mldsa_65_sa_algo:
6423
            *sigAlgo = ML_DSA_65k;
6424
            break;
6425
        case mldsa_87_sa_algo:
6426
            *sigAlgo = ML_DSA_87k;
6427
            break;
6428
        case sm2_sa_algo:
6429
            *sigAlgo = SM2k;
6430
            break;
6431
        case invalid_sa_algo:
6432
        case any_sa_algo:
6433
        default:
6434
            *hashAlgo = WC_HASH_TYPE_NONE;
6435
            *sigAlgo = 0;
6436
            return BAD_FUNC_ARG;
6437
        }
6438
6439
        /* cast so that compiler reminds us of unimplemented values */
6440
        switch((enum wc_MACAlgorithm)hashType) {
6441
        case no_mac:
6442
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
6443
            *hashAlgo = WC_HASH_TYPE_NONE;
6444
            break;
6445
        case md5_mac:
6446
            *hashAlgo = WC_HASH_TYPE_MD5;
6447
            break;
6448
        case sha_mac:
6449
            *hashAlgo = WC_HASH_TYPE_SHA;
6450
            break;
6451
        case sha224_mac:
6452
            *hashAlgo = WC_HASH_TYPE_SHA224;
6453
            break;
6454
        case sha256_mac:
6455
            *hashAlgo = WC_HASH_TYPE_SHA256;
6456
            break;
6457
        case sha384_mac:
6458
            *hashAlgo = WC_HASH_TYPE_SHA384;
6459
            break;
6460
        case sha512_mac:
6461
            *hashAlgo = WC_HASH_TYPE_SHA512;
6462
            break;
6463
        case blake2b_mac:
6464
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
6465
            break;
6466
        case sm3_mac:
6467
#ifdef WOLFSSL_SM3
6468
            *hashAlgo = WC_HASH_TYPE_SM3;
6469
#else
6470
            *hashAlgo = WC_HASH_TYPE_NONE;
6471
#endif
6472
            break;
6473
        default:
6474
            *hashAlgo = WC_HASH_TYPE_NONE;
6475
            *sigAlgo = 0;
6476
            return BAD_FUNC_ARG;
6477
        }
6478
        return 0;
6479
    }
6480
6481
    /**
6482
     * Internal wrapper for calling certSetupCb
6483
     * @param ssl The SSL/TLS Object
6484
     * @return 0 on success
6485
     */
6486
    int CertSetupCbWrapper(WOLFSSL* ssl)
6487
    {
6488
        int ret = 0;
6489
        if (ssl->ctx->certSetupCb != NULL) {
6490
            WOLFSSL_MSG("Calling user cert setup callback");
6491
            ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg);
6492
            if (ret == 1) {
6493
                WOLFSSL_MSG("User cert callback returned success");
6494
                ret = 0;
6495
            }
6496
            else if (ret == 0) {
6497
                SendAlert(ssl, alert_fatal, internal_error);
6498
                ret = CLIENT_CERT_CB_ERROR;
6499
            }
6500
            else if (ret < 0) {
6501
                ret = WOLFSSL_ERROR_WANT_X509_LOOKUP;
6502
            }
6503
            else {
6504
                WOLFSSL_MSG("Unexpected user callback return");
6505
                ret = CLIENT_CERT_CB_ERROR;
6506
            }
6507
        }
6508
        return ret;
6509
    }
6510
#endif /* WOLFSSL_CERT_SETUP_CB */
6511
6512
#ifdef OPENSSL_EXTRA
6513
6514
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
6515
        && !defined(WC_NO_RNG)
6516
    static const byte srp_N[] = {
6517
        0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8,
6518
        0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF,
6519
        0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6,
6520
        0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13,
6521
        0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B,
6522
        0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7,
6523
        0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69,
6524
        0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85,
6525
        0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC,
6526
        0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E,
6527
        0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F,
6528
        0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3
6529
    };
6530
    static const byte srp_g[] = {
6531
        0x02
6532
    };
6533
6534
    int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username)
6535
    {
6536
        int r = 0;
6537
        SrpSide srp_side = SRP_CLIENT_SIDE;
6538
6539
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username");
6540
        if (ctx == NULL || ctx->srp == NULL || username==NULL)
6541
            return WOLFSSL_FAILURE;
6542
6543
        if (ctx->method->side == WOLFSSL_SERVER_END){
6544
            srp_side = SRP_SERVER_SIDE;
6545
        } else if (ctx->method->side == WOLFSSL_CLIENT_END){
6546
            srp_side = SRP_CLIENT_SIDE;
6547
        } else {
6548
            WOLFSSL_MSG("Init CTX failed");
6549
            return WOLFSSL_FAILURE;
6550
        }
6551
6552
        if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) {
6553
            WOLFSSL_MSG("Init SRP CTX failed");
6554
            XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
6555
            ctx->srp = NULL;
6556
            return WOLFSSL_FAILURE;
6557
        }
6558
        r = wc_SrpSetUsername(ctx->srp, (const byte*)username,
6559
                              (word32)XSTRLEN(username));
6560
        if (r < 0) {
6561
            WOLFSSL_MSG("fail to set srp username.");
6562
            return WOLFSSL_FAILURE;
6563
        }
6564
6565
        /* if wolfSSL_CTX_set_srp_password has already been called, */
6566
        /* use saved password here */
6567
        if (ctx->srp_password != NULL) {
6568
            if (ctx->srp->user == NULL)
6569
                return WOLFSSL_FAILURE;
6570
            return wolfSSL_CTX_set_srp_password(ctx, (char*)ctx->srp_password);
6571
        }
6572
6573
        return WOLFSSL_SUCCESS;
6574
    }
6575
6576
    int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password)
6577
    {
6578
        int r;
6579
        byte salt[SRP_SALT_SIZE];
6580
6581
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password");
6582
        if (ctx == NULL || ctx->srp == NULL || password == NULL)
6583
            return WOLFSSL_FAILURE;
6584
6585
        if (ctx->srp->user != NULL) {
6586
            WC_RNG rng;
6587
            if (wc_InitRng(&rng) < 0) {
6588
                WOLFSSL_MSG("wc_InitRng failed");
6589
                return WOLFSSL_FAILURE;
6590
            }
6591
            XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
6592
            r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
6593
            wc_FreeRng(&rng);
6594
            if (r <  0) {
6595
                WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
6596
                return WOLFSSL_FAILURE;
6597
            }
6598
            if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
6599
                                srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
6600
                                salt, sizeof(salt)/sizeof(salt[0])) < 0){
6601
                WOLFSSL_MSG("wc_SrpSetParam failed");
6602
                return WOLFSSL_FAILURE;
6603
            }
6604
            r = wc_SrpSetPassword(ctx->srp, (const byte*)password,
6605
                                  (word32)XSTRLEN(password));
6606
            if (r < 0) {
6607
                WOLFSSL_MSG("wc_SrpSetPassword failed.");
6608
                return WOLFSSL_FAILURE;
6609
            }
6610
            XFREE(ctx->srp_password, NULL, DYNAMIC_TYPE_SRP);
6611
            ctx->srp_password = NULL;
6612
        } else {
6613
            /* save password for wolfSSL_set_srp_username */
6614
            XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
6615
6616
            ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap,
6617
                                               DYNAMIC_TYPE_SRP);
6618
            if (ctx->srp_password == NULL){
6619
                WOLFSSL_MSG("memory allocation error");
6620
                return WOLFSSL_FAILURE;
6621
            }
6622
            XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1);
6623
        }
6624
        return WOLFSSL_SUCCESS;
6625
    }
6626
6627
    /**
6628
     * The modulus passed to wc_SrpSetParams in ssl.c is constant so check
6629
     * that the requested strength is less than or equal to the size of the
6630
     * static modulus size.
6631
     * @param ctx Not used
6632
     * @param strength Minimum number of bits for the modulus
6633
     * @return 1 if strength is less than or equal to static modulus
6634
     *         0 if strength is greater than static modulus
6635
     */
6636
    int  wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength)
6637
    {
6638
        (void)ctx;
6639
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength");
6640
        if (strength > (int)(sizeof(srp_N)*8)) {
6641
            WOLFSSL_MSG("Bad Parameter");
6642
            return WOLFSSL_FAILURE;
6643
        }
6644
        return WOLFSSL_SUCCESS;
6645
    }
6646
6647
    char* wolfSSL_get_srp_username(WOLFSSL *ssl)
6648
    {
6649
        if (ssl && ssl->ctx && ssl->ctx->srp) {
6650
            return (char*) ssl->ctx->srp->user;
6651
        }
6652
        return NULL;
6653
    }
6654
    #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */
6655
6656
    /* keyblock size in bytes or -1 */
6657
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
6658
    {
6659
        if (ssl == NULL)
6660
            return WOLFSSL_FATAL_ERROR;
6661
6662
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
6663
                    ssl->specs.hash_size);
6664
    }
6665
6666
#endif /* OPENSSL_EXTRA */
6667
6668
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
6669
    defined(WOLFSSL_WPAS_SMALL)
6670
6671
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
6672
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
6673
                                     unsigned char** sr, unsigned int* srLen,
6674
                                     unsigned char** cr, unsigned int* crLen)
6675
    {
6676
        if (ssl == NULL || ssl->arrays == NULL)
6677
            return WOLFSSL_FATAL_ERROR;
6678
6679
        *ms = ssl->arrays->masterSecret;
6680
        *sr = ssl->arrays->serverRandom;
6681
        *cr = ssl->arrays->clientRandom;
6682
6683
        *msLen = SECRET_LEN;
6684
        *srLen = RAN_LEN;
6685
        *crLen = RAN_LEN;
6686
6687
        return WOLFSSL_SUCCESS;
6688
    }
6689
6690
    void wolfSSL_set_accept_state(WOLFSSL* ssl)
6691
    {
6692
        WOLFSSL_ENTER("wolfSSL_set_accept_state");
6693
6694
        if (ssl == NULL)
6695
            return;
6696
6697
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
6698
    #ifdef HAVE_ECC
6699
            WC_DECLARE_VAR(key, ecc_key, 1, 0);
6700
            word32 idx = 0;
6701
6702
        #ifdef WOLFSSL_SMALL_STACK
6703
            key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
6704
                                    DYNAMIC_TYPE_ECC);
6705
            if (key == NULL) {
6706
                WOLFSSL_MSG("Error allocating memory for ecc_key");
6707
            }
6708
        #endif
6709
            if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) {
6710
                if (wc_ecc_init(key) >= 0) {
6711
                    if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
6712
                            key, ssl->buffers.key->length) != 0) {
6713
                        ssl->options.haveECDSAsig = 0;
6714
                        ssl->options.haveECC = 0;
6715
                        ssl->options.haveStaticECC = 0;
6716
                    }
6717
                    wc_ecc_free(key);
6718
                }
6719
            }
6720
            WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
6721
    #endif
6722
6723
    #ifndef NO_DH
6724
            if (!ssl->options.haveDH && ssl->ctx->haveDH) {
6725
                ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
6726
                ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
6727
                ssl->options.haveDH = 1;
6728
            }
6729
    #endif
6730
        }
6731
6732
        if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
6733
            WOLFSSL_MSG("Error initializing server side");
6734
        }
6735
    }
6736
6737
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
6738
6739
    /* return true if connection established */
6740
    /* this works for TLS and DTLS */
6741
    int wolfSSL_is_init_finished(const WOLFSSL* ssl)
6742
0
    {
6743
0
        if (ssl == NULL)
6744
0
            return 0;
6745
6746
#if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
6747
        if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls
6748
                && IsAtLeastTLSv1_3(ssl->version)) {
6749
            return ssl->options.serverState == SERVER_FINISHED_ACKED;
6750
        }
6751
#endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT */
6752
6753
        /* Can't use ssl->options.connectState and ssl->options.acceptState
6754
         * because they differ in meaning for TLS <=1.2 and 1.3 */
6755
0
        if (ssl->options.handShakeState == HANDSHAKE_DONE)
6756
0
            return 1;
6757
6758
0
        return 0;
6759
0
    }
6760
6761
#ifdef OPENSSL_EXTRA
6762
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
6763
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
6764
    {
6765
        /* wolfSSL verifies all these internally */
6766
        (void)ctx;
6767
        (void)f;
6768
    }
6769
6770
6771
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
6772
    {
6773
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
6774
        if(ssl==NULL) {
6775
            WOLFSSL_MSG("Shutdown not set. ssl is null");
6776
            return;
6777
        }
6778
6779
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
6780
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
6781
    }
6782
#endif
6783
6784
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
6785
0
    {
6786
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
6787
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
6788
0
        if(ctx == NULL)
6789
0
            return BAD_FUNC_ARG;
6790
0
        return (long)ctx->mask;
6791
0
    }
6792
6793
    /* forward declaration */
6794
    static long wolf_set_options(long old_op, long op);
6795
6796
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
6797
0
    {
6798
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
6799
6800
0
        if (ctx == NULL)
6801
0
            return BAD_FUNC_ARG;
6802
6803
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
6804
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
6805
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
6806
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
6807
          ctx->noTicketTls12 = 1;
6808
        }
6809
        /* This code is here for documentation purpose. You must not turn off
6810
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
6811
         * Because we need to support both stateful and stateless tickets.
6812
        #ifdef WOLFSSL_TLS13
6813
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
6814
                ctx->noTicketTls13 = 1;
6815
            }
6816
        #endif
6817
        */
6818
#endif
6819
0
        return (long)ctx->mask;
6820
0
    }
6821
6822
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
6823
0
    {
6824
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
6825
0
        if(ctx == NULL)
6826
0
            return BAD_FUNC_ARG;
6827
0
        ctx->mask &= (unsigned long)~opt;
6828
0
        return (long)ctx->mask;
6829
0
    }
6830
6831
#ifdef OPENSSL_EXTRA
6832
6833
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
6834
    {
6835
        WOLFSSL_ENTER("wolfSSL_set_rfd");
6836
        ssl->rfd = rfd;      /* not used directly to allow IO callbacks */
6837
6838
        ssl->IOCB_ReadCtx  = &ssl->rfd;
6839
6840
    #ifdef WOLFSSL_DTLS
6841
        if (ssl->options.dtls) {
6842
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
6843
            ssl->buffers.dtlsCtx.rfd = rfd;
6844
        #ifdef USE_WOLFSSL_IO
6845
            ssl->buffers.dtlsCtx.rfdIsDGram =
6846
                (byte)(wolfIO_SockIsDGram(rfd) != 0);
6847
        #endif
6848
        }
6849
    #endif
6850
6851
        return WOLFSSL_SUCCESS;
6852
    }
6853
6854
6855
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
6856
    {
6857
        WOLFSSL_ENTER("wolfSSL_set_wfd");
6858
        ssl->wfd = wfd;      /* not used directly to allow IO callbacks */
6859
6860
        ssl->IOCB_WriteCtx  = &ssl->wfd;
6861
6862
        return WOLFSSL_SUCCESS;
6863
    }
6864
#endif /* OPENSSL_EXTRA */
6865
6866
#ifdef WOLFSSL_ENCRYPTED_KEYS
6867
6868
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
6869
                                                   void* userdata)
6870
    {
6871
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
6872
        if (ctx)
6873
            ctx->passwd_userdata = userdata;
6874
    }
6875
6876
6877
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
6878
                                           cb)
6879
    {
6880
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
6881
        if (ctx)
6882
            ctx->passwd_cb = cb;
6883
    }
6884
6885
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
6886
    {
6887
        if (ctx == NULL || ctx->passwd_cb == NULL) {
6888
            return NULL;
6889
        }
6890
6891
        return ctx->passwd_cb;
6892
    }
6893
6894
6895
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
6896
    {
6897
        if (ctx == NULL) {
6898
            return NULL;
6899
        }
6900
6901
        return ctx->passwd_userdata;
6902
    }
6903
6904
#endif /* WOLFSSL_ENCRYPTED_KEYS */
6905
6906
6907
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
6908
    unsigned long wolfSSL_ERR_get_error(void)
6909
    {
6910
        WOLFSSL_ENTER("wolfSSL_ERR_get_error");
6911
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
6912
        return (unsigned long)wc_GetErrorNodeErr();
6913
#else
6914
        return (unsigned long)(0 - NOT_COMPILED_IN);
6915
#endif
6916
    }
6917
#endif
6918
6919
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
6920
6921
    int wolfSSL_num_locks(void)
6922
    {
6923
        return 0;
6924
    }
6925
6926
    void wolfSSL_set_locking_callback(mutex_cb* f)
6927
    {
6928
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
6929
6930
        if (wc_SetMutexCb(f) != 0) {
6931
            WOLFSSL_MSG("Error when setting mutex call back");
6932
        }
6933
    }
6934
6935
    mutex_cb* wolfSSL_get_locking_callback(void)
6936
    {
6937
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
6938
6939
        return wc_GetMutexCb();
6940
    }
6941
6942
6943
    typedef unsigned long (idCb)(void);
6944
    static idCb* inner_idCb = NULL;
6945
6946
    unsigned long wolfSSL_thread_id(void)
6947
    {
6948
        if (inner_idCb != NULL) {
6949
            return inner_idCb();
6950
        }
6951
        else {
6952
            return 0;
6953
        }
6954
    }
6955
6956
6957
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
6958
    {
6959
        inner_idCb = f;
6960
    }
6961
6962
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
6963
#ifndef NO_BIO
6964
    /* print out and clear all errors */
6965
    void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio)
6966
    {
6967
        const char* file = NULL;
6968
        const char* reason = NULL;
6969
        int ret;
6970
        int line = 0;
6971
        char buf[WOLFSSL_MAX_ERROR_SZ * 2];
6972
6973
        WOLFSSL_ENTER("wolfSSL_ERR_print_errors");
6974
6975
        if (bio == NULL) {
6976
            WOLFSSL_MSG("BIO passed in was null");
6977
            return;
6978
        }
6979
6980
        do {
6981
        ret = wc_PeekErrorNode(0, &file, &reason, &line);
6982
        if (ret >= 0) {
6983
            const char* r = wolfSSL_ERR_reason_error_string(
6984
                (unsigned long)(0 - ret));
6985
            if (XSNPRINTF(buf, sizeof(buf),
6986
                          "error:%d:wolfSSL library:%s:%s:%d\n",
6987
                          ret, r, file, line)
6988
                >= (int)sizeof(buf))
6989
            {
6990
                WOLFSSL_MSG("Buffer overrun formatting error message");
6991
            }
6992
            wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf));
6993
            wc_RemoveErrorNode(0);
6994
        }
6995
        } while (ret >= 0);
6996
        if (wolfSSL_BIO_write(bio, "", 1) != 1) {
6997
            WOLFSSL_MSG("Issue writing final string terminator");
6998
        }
6999
    }
7000
#endif /* !NO_BIO */
7001
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
7002
7003
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
7004
7005
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
7006
    defined(HAVE_SECRET_CALLBACK)
7007
#if !defined(NO_WOLFSSL_SERVER)
7008
/* Return the amount of random bytes copied over or error case.
7009
 * ssl : ssl struct after handshake
7010
 * out : buffer to hold random bytes
7011
 * outSz : either 0 (return max buffer sz) or size of out buffer
7012
 */
7013
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
7014
                                                                   size_t outSz)
7015
{
7016
    size_t size;
7017
7018
    /* return max size of buffer */
7019
    if (outSz == 0) {
7020
        return RAN_LEN;
7021
    }
7022
7023
    if (ssl == NULL || out == NULL) {
7024
        return 0;
7025
    }
7026
7027
    if (ssl->arrays == NULL) {
7028
        WOLFSSL_MSG("Arrays struct not saved after handshake");
7029
        return 0;
7030
    }
7031
7032
    if (outSz > RAN_LEN) {
7033
        size = RAN_LEN;
7034
    }
7035
    else {
7036
        size = outSz;
7037
    }
7038
7039
    XMEMCPY(out, ssl->arrays->serverRandom, size);
7040
    return size;
7041
}
7042
#endif /* !NO_WOLFSSL_SERVER */
7043
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
7044
7045
#ifdef OPENSSL_EXTRA
7046
#if !defined(NO_WOLFSSL_SERVER)
7047
/* Used to get the peer ephemeral public key sent during the connection
7048
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
7049
 *       before the ephemeral key is stored.
7050
 * return WOLFSSL_SUCCESS on success */
7051
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
7052
{
7053
    WOLFSSL_EVP_PKEY* ret = NULL;
7054
7055
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
7056
7057
    if (ssl == NULL || pkey == NULL) {
7058
        WOLFSSL_MSG("Bad argument passed in");
7059
        return WOLFSSL_FAILURE;
7060
    }
7061
7062
#ifdef HAVE_ECC
7063
    if (ssl->peerEccKey != NULL) {
7064
        unsigned char* der;
7065
        const unsigned char* pt;
7066
        unsigned int   derSz = 0;
7067
        int sz;
7068
7069
        PRIVATE_KEY_UNLOCK();
7070
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
7071
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
7072
        {
7073
            WOLFSSL_MSG("get ecc der size failed");
7074
            PRIVATE_KEY_LOCK();
7075
            return WOLFSSL_FAILURE;
7076
        }
7077
        PRIVATE_KEY_LOCK();
7078
7079
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
7080
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
7081
        if (der == NULL) {
7082
            WOLFSSL_MSG("Memory error");
7083
            return WOLFSSL_FAILURE;
7084
        }
7085
7086
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
7087
            WOLFSSL_MSG("get ecc der failed");
7088
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
7089
            return WOLFSSL_FAILURE;
7090
        }
7091
        pt = der; /* in case pointer gets advanced */
7092
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
7093
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
7094
    }
7095
#endif
7096
7097
    *pkey = ret;
7098
#ifdef HAVE_ECC
7099
    if (ret != NULL)
7100
        return WOLFSSL_SUCCESS;
7101
    else
7102
#endif
7103
        return WOLFSSL_FAILURE;
7104
}
7105
7106
#endif /* !NO_WOLFSSL_SERVER */
7107
7108
/**
7109
 * This function checks if any compiled in protocol versions are
7110
 * left enabled after calls to set_min or set_max API.
7111
 * @param major The SSL/TLS major version
7112
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7113
 *         protocol versions are left enabled.
7114
 */
7115
static int CheckSslMethodVersion(byte major, unsigned long options)
7116
{
7117
    int sanityConfirmed = 0;
7118
7119
    (void)options;
7120
7121
    switch (major) {
7122
    #ifndef NO_TLS
7123
        case SSLv3_MAJOR:
7124
            #ifdef WOLFSSL_ALLOW_SSLV3
7125
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
7126
                    sanityConfirmed = 1;
7127
                }
7128
            #endif
7129
            #ifndef NO_OLD_TLS
7130
                if (!(options & WOLFSSL_OP_NO_TLSv1))
7131
                    sanityConfirmed = 1;
7132
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
7133
                    sanityConfirmed = 1;
7134
            #endif
7135
            #ifndef WOLFSSL_NO_TLS12
7136
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
7137
                    sanityConfirmed = 1;
7138
            #endif
7139
            #ifdef WOLFSSL_TLS13
7140
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
7141
                    sanityConfirmed = 1;
7142
            #endif
7143
            break;
7144
    #endif
7145
    #ifdef WOLFSSL_DTLS
7146
        case DTLS_MAJOR:
7147
            sanityConfirmed = 1;
7148
            break;
7149
    #endif
7150
        default:
7151
            WOLFSSL_MSG("Invalid major version");
7152
            return WOLFSSL_FAILURE;
7153
    }
7154
    if (!sanityConfirmed) {
7155
        WOLFSSL_MSG("All compiled in TLS versions disabled");
7156
        return WOLFSSL_FAILURE;
7157
    }
7158
    return WOLFSSL_SUCCESS;
7159
}
7160
7161
/**
7162
 * protoVerTbl holds (D)TLS version numbers in ascending order.
7163
 * Except DTLS versions, the newer version is located in the latter part of
7164
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
7165
 * wolfSSL_CTX_set_max_proto_version.
7166
 */
7167
static const int protoVerTbl[] = {
7168
    SSL3_VERSION,
7169
    TLS1_VERSION,
7170
    TLS1_1_VERSION,
7171
    TLS1_2_VERSION,
7172
    TLS1_3_VERSION,
7173
    DTLS1_VERSION,
7174
    DTLS1_2_VERSION
7175
};
7176
/* number of protocol versions listed in protoVerTbl */
7177
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
7178
7179
/**
7180
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
7181
 * version to use by SSL objects created from this WOLFSSL_CTX.
7182
 * This API guarantees that a version of SSL/TLS lower than specified
7183
 * here will not be allowed. If the version specified is not compiled in
7184
 * then this API sets the lowest compiled in protocol version.
7185
 * This API also accept 0 as version, to set the minimum version automatically.
7186
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
7187
 * are enabled.
7188
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
7189
 * @param version Any of the following
7190
 *          * 0
7191
 *          * SSL3_VERSION
7192
 *          * TLS1_VERSION
7193
 *          * TLS1_1_VERSION
7194
 *          * TLS1_2_VERSION
7195
 *          * TLS1_3_VERSION
7196
 *          * DTLS1_VERSION
7197
 *          * DTLS1_2_VERSION
7198
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7199
 *         protocol versions are left enabled.
7200
 */
7201
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
7202
{
7203
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
7204
7205
    if (ctx == NULL) {
7206
        return WOLFSSL_FAILURE;
7207
    }
7208
7209
    switch (version) {
7210
#ifndef NO_TLS
7211
        case SSL3_VERSION:
7212
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
7213
            ctx->minDowngrade = SSLv3_MINOR;
7214
            break;
7215
#endif
7216
        case TLS1_VERSION:
7217
        #ifdef WOLFSSL_ALLOW_TLSV10
7218
            ctx->minDowngrade = TLSv1_MINOR;
7219
            break;
7220
        #endif
7221
        case TLS1_1_VERSION:
7222
        #ifndef NO_OLD_TLS
7223
            ctx->minDowngrade = TLSv1_1_MINOR;
7224
            break;
7225
        #endif
7226
        case TLS1_2_VERSION:
7227
        #ifndef WOLFSSL_NO_TLS12
7228
            ctx->minDowngrade = TLSv1_2_MINOR;
7229
            break;
7230
        #endif
7231
        case TLS1_3_VERSION:
7232
        #ifdef WOLFSSL_TLS13
7233
            ctx->minDowngrade = TLSv1_3_MINOR;
7234
            break;
7235
        #endif
7236
#endif
7237
#ifdef WOLFSSL_DTLS
7238
        case DTLS1_VERSION:
7239
    #ifndef NO_OLD_TLS
7240
            ctx->minDowngrade = DTLS_MINOR;
7241
            break;
7242
    #endif
7243
        case DTLS1_2_VERSION:
7244
            ctx->minDowngrade = DTLSv1_2_MINOR;
7245
            break;
7246
#endif
7247
        default:
7248
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7249
            return WOLFSSL_FAILURE;
7250
    }
7251
7252
    switch (version) {
7253
#ifndef NO_TLS
7254
    case TLS1_3_VERSION:
7255
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
7256
        FALL_THROUGH;
7257
    case TLS1_2_VERSION:
7258
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
7259
        FALL_THROUGH;
7260
    case TLS1_1_VERSION:
7261
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
7262
        FALL_THROUGH;
7263
    case TLS1_VERSION:
7264
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
7265
        break;
7266
    case SSL3_VERSION:
7267
    case SSL2_VERSION:
7268
        /* Nothing to do here */
7269
        break;
7270
#endif
7271
#ifdef WOLFSSL_DTLS
7272
    case DTLS1_VERSION:
7273
    case DTLS1_2_VERSION:
7274
        break;
7275
#endif
7276
    default:
7277
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7278
        return WOLFSSL_FAILURE;
7279
    }
7280
7281
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
7282
}
7283
7284
/* Sets the min protocol version allowed with WOLFSSL_CTX
7285
 * returns WOLFSSL_SUCCESS on success */
7286
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
7287
{
7288
    int ret;
7289
    int proto    = 0;
7290
    int maxProto = 0;
7291
    int i;
7292
    int idx = 0;
7293
7294
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
7295
7296
    if (ctx == NULL) {
7297
        return WOLFSSL_FAILURE;
7298
    }
7299
7300
    if (version != 0) {
7301
        proto = version;
7302
        ctx->minProto = 0; /* turn min proto flag off */
7303
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7304
            if (protoVerTbl[i] == version) {
7305
                break;
7306
            }
7307
        }
7308
    }
7309
    else {
7310
        /* when 0 is specified as version, try to find out the min version */
7311
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7312
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
7313
            if (ret == WOLFSSL_SUCCESS) {
7314
                proto = protoVerTbl[i];
7315
                ctx->minProto = 1; /* turn min proto flag on */
7316
                break;
7317
            }
7318
        }
7319
    }
7320
7321
    /* check case where max > min , if so then clear the NO_* options
7322
     * i is the index into the table for proto version used, see if the max
7323
     * proto version index found is smaller */
7324
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
7325
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
7326
        if (protoVerTbl[idx] == maxProto) {
7327
            break;
7328
        }
7329
    }
7330
    if (idx < i) {
7331
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
7332
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
7333
                WOLFSSL_OP_NO_TLSv1_3);
7334
    }
7335
7336
    ret = Set_CTX_min_proto_version(ctx, proto);
7337
    return ret;
7338
}
7339
7340
/**
7341
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
7342
 * version to use by SSL objects created from this WOLFSSL_CTX.
7343
 * This API guarantees that a version of SSL/TLS higher than specified
7344
 * here will not be allowed. If the version specified is not compiled in
7345
 * then this API sets the highest compiled in protocol version.
7346
 * This API also accept 0 as version, to set the maximum version automatically.
7347
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
7348
 * are enabled.
7349
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
7350
 * @param ver Any of the following
7351
 *          * 0
7352
 *          * SSL3_VERSION
7353
 *          * TLS1_VERSION
7354
 *          * TLS1_1_VERSION
7355
 *          * TLS1_2_VERSION
7356
 *          * TLS1_3_VERSION
7357
 *          * DTLS1_VERSION
7358
 *          * DTLS1_2_VERSION
7359
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7360
 *         protocol versions are left enabled.
7361
 */
7362
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
7363
{
7364
    int ret;
7365
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
7366
7367
    if (!ctx || !ctx->method) {
7368
        WOLFSSL_MSG("Bad parameter");
7369
        return WOLFSSL_FAILURE;
7370
    }
7371
7372
    switch (ver) {
7373
#ifndef NO_TLS
7374
#ifndef NO_OLD_TLS
7375
    case SSL2_VERSION:
7376
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
7377
        return WOLFSSL_FAILURE;
7378
#endif
7379
    case SSL3_VERSION:
7380
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
7381
        FALL_THROUGH;
7382
    case TLS1_VERSION:
7383
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
7384
        FALL_THROUGH;
7385
    case TLS1_1_VERSION:
7386
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
7387
        FALL_THROUGH;
7388
    case TLS1_2_VERSION:
7389
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
7390
        FALL_THROUGH;
7391
    case TLS1_3_VERSION:
7392
        /* Nothing to do here */
7393
        break;
7394
#endif
7395
#ifdef WOLFSSL_DTLS
7396
    case DTLS1_VERSION:
7397
    case DTLS1_2_VERSION:
7398
        break;
7399
#endif
7400
    default:
7401
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7402
        return WOLFSSL_FAILURE;
7403
    }
7404
7405
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
7406
    if (ret == WOLFSSL_SUCCESS) {
7407
        /* Check the major */
7408
        switch (ver) {
7409
    #ifndef NO_TLS
7410
        case SSL3_VERSION:
7411
        case TLS1_VERSION:
7412
        case TLS1_1_VERSION:
7413
        case TLS1_2_VERSION:
7414
        case TLS1_3_VERSION:
7415
            if (ctx->method->version.major != SSLv3_MAJOR) {
7416
                WOLFSSL_MSG("Mismatched protocol version");
7417
                return WOLFSSL_FAILURE;
7418
            }
7419
            break;
7420
    #endif
7421
    #ifdef WOLFSSL_DTLS
7422
        case DTLS1_VERSION:
7423
        case DTLS1_2_VERSION:
7424
            if (ctx->method->version.major != DTLS_MAJOR) {
7425
                WOLFSSL_MSG("Mismatched protocol version");
7426
                return WOLFSSL_FAILURE;
7427
            }
7428
            break;
7429
    #endif
7430
        }
7431
        /* Update the method */
7432
        switch (ver) {
7433
    #ifndef NO_TLS
7434
        case SSL3_VERSION:
7435
            ctx->method->version.minor = SSLv3_MINOR;
7436
            break;
7437
        case TLS1_VERSION:
7438
            ctx->method->version.minor = TLSv1_MINOR;
7439
            break;
7440
        case TLS1_1_VERSION:
7441
            ctx->method->version.minor = TLSv1_1_MINOR;
7442
            break;
7443
        case TLS1_2_VERSION:
7444
            ctx->method->version.minor = TLSv1_2_MINOR;
7445
            break;
7446
        case TLS1_3_VERSION:
7447
            ctx->method->version.minor = TLSv1_3_MINOR;
7448
            break;
7449
    #endif
7450
    #ifdef WOLFSSL_DTLS
7451
        case DTLS1_VERSION:
7452
            ctx->method->version.minor = DTLS_MINOR;
7453
            break;
7454
        case DTLS1_2_VERSION:
7455
            ctx->method->version.minor = DTLSv1_2_MINOR;
7456
            break;
7457
    #endif
7458
        default:
7459
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7460
            return WOLFSSL_FAILURE;
7461
        }
7462
    }
7463
    return ret;
7464
}
7465
7466
7467
/* Sets the max protocol version allowed with WOLFSSL_CTX
7468
 * returns WOLFSSL_SUCCESS on success */
7469
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
7470
{
7471
    int i;
7472
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
7473
    int minProto;
7474
7475
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
7476
7477
    if (ctx == NULL) {
7478
        return ret;
7479
    }
7480
7481
    /* clear out flags and reset min protocol version */
7482
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
7483
    wolfSSL_CTX_clear_options(ctx,
7484
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
7485
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
7486
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
7487
    if (version != 0) {
7488
        ctx->maxProto = 0; /* turn max proto flag off */
7489
        return Set_CTX_max_proto_version(ctx, version);
7490
    }
7491
7492
    /* when 0 is specified as version, try to find out the min version from
7493
     * the bottom to top of the protoverTbl.
7494
     */
7495
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
7496
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
7497
        if (ret == WOLFSSL_SUCCESS) {
7498
            ctx->maxProto = 1; /* turn max proto flag on */
7499
            break;
7500
        }
7501
    }
7502
7503
    return ret;
7504
}
7505
7506
7507
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
7508
{
7509
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
7510
7511
    if (ssl == NULL) {
7512
        return WOLFSSL_FAILURE;
7513
    }
7514
7515
    switch (ver) {
7516
#ifndef NO_TLS
7517
        case SSL3_VERSION:
7518
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
7519
            ssl->options.minDowngrade = SSLv3_MINOR;
7520
            break;
7521
#endif
7522
        case TLS1_VERSION:
7523
        #ifdef WOLFSSL_ALLOW_TLSV10
7524
            ssl->options.minDowngrade = TLSv1_MINOR;
7525
            break;
7526
        #endif
7527
        case TLS1_1_VERSION:
7528
        #ifndef NO_OLD_TLS
7529
            ssl->options.minDowngrade = TLSv1_1_MINOR;
7530
            break;
7531
        #endif
7532
        case TLS1_2_VERSION:
7533
        #ifndef WOLFSSL_NO_TLS12
7534
            ssl->options.minDowngrade = TLSv1_2_MINOR;
7535
            break;
7536
        #endif
7537
        case TLS1_3_VERSION:
7538
        #ifdef WOLFSSL_TLS13
7539
            ssl->options.minDowngrade = TLSv1_3_MINOR;
7540
            break;
7541
        #endif
7542
#endif
7543
#ifdef WOLFSSL_DTLS
7544
        case DTLS1_VERSION:
7545
    #ifndef NO_OLD_TLS
7546
            ssl->options.minDowngrade = DTLS_MINOR;
7547
            break;
7548
    #endif
7549
        case DTLS1_2_VERSION:
7550
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
7551
            break;
7552
#endif
7553
        default:
7554
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7555
            return WOLFSSL_FAILURE;
7556
    }
7557
7558
    switch (ver) {
7559
#ifndef NO_TLS
7560
    case TLS1_3_VERSION:
7561
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
7562
        FALL_THROUGH;
7563
    case TLS1_2_VERSION:
7564
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
7565
        FALL_THROUGH;
7566
    case TLS1_1_VERSION:
7567
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
7568
        FALL_THROUGH;
7569
    case TLS1_VERSION:
7570
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
7571
        break;
7572
    case SSL3_VERSION:
7573
    case SSL2_VERSION:
7574
        /* Nothing to do here */
7575
        break;
7576
#endif
7577
#ifdef WOLFSSL_DTLS
7578
    case DTLS1_VERSION:
7579
    case DTLS1_2_VERSION:
7580
        break;
7581
#endif
7582
    default:
7583
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7584
        return WOLFSSL_FAILURE;
7585
    }
7586
7587
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
7588
}
7589
7590
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
7591
{
7592
    int i;
7593
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
7594
7595
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
7596
7597
    if (ssl == NULL) {
7598
        return WOLFSSL_FAILURE;
7599
    }
7600
    if (version != 0) {
7601
        return Set_SSL_min_proto_version(ssl, version);
7602
    }
7603
7604
    /* when 0 is specified as version, try to find out the min version */
7605
    for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7606
        ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
7607
        if (ret == WOLFSSL_SUCCESS)
7608
            break;
7609
    }
7610
7611
    return ret;
7612
}
7613
7614
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
7615
{
7616
7617
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
7618
7619
    if (!ssl) {
7620
        WOLFSSL_MSG("Bad parameter");
7621
        return WOLFSSL_FAILURE;
7622
    }
7623
7624
    switch (ver) {
7625
    case SSL2_VERSION:
7626
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
7627
        return WOLFSSL_FAILURE;
7628
#ifndef NO_TLS
7629
    case SSL3_VERSION:
7630
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
7631
        FALL_THROUGH;
7632
    case TLS1_VERSION:
7633
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
7634
        FALL_THROUGH;
7635
    case TLS1_1_VERSION:
7636
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
7637
        FALL_THROUGH;
7638
    case TLS1_2_VERSION:
7639
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
7640
        FALL_THROUGH;
7641
    case TLS1_3_VERSION:
7642
        /* Nothing to do here */
7643
        break;
7644
#endif
7645
#ifdef WOLFSSL_DTLS
7646
    case DTLS1_VERSION:
7647
    case DTLS1_2_VERSION:
7648
        break;
7649
#endif
7650
    default:
7651
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7652
        return WOLFSSL_FAILURE;
7653
    }
7654
7655
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
7656
}
7657
7658
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
7659
{
7660
    int i;
7661
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
7662
7663
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
7664
7665
    if (ssl == NULL) {
7666
        return WOLFSSL_FAILURE;
7667
    }
7668
    if (version != 0) {
7669
        return Set_SSL_max_proto_version(ssl, version);
7670
    }
7671
7672
    /* when 0 is specified as version, try to find out the min version from
7673
     * the bottom to top of the protoverTbl.
7674
     */
7675
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
7676
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
7677
        if (ret == WOLFSSL_SUCCESS)
7678
            break;
7679
    }
7680
7681
    return ret;
7682
}
7683
7684
static int GetMinProtoVersion(int minDowngrade)
7685
{
7686
    int ret;
7687
7688
    switch (minDowngrade) {
7689
#ifndef NO_OLD_TLS
7690
    #ifdef WOLFSSL_ALLOW_SSLV3
7691
        case SSLv3_MINOR:
7692
            ret = SSL3_VERSION;
7693
            break;
7694
    #endif
7695
    #ifdef WOLFSSL_ALLOW_TLSV10
7696
        case TLSv1_MINOR:
7697
            ret = TLS1_VERSION;
7698
            break;
7699
    #endif
7700
        case TLSv1_1_MINOR:
7701
            ret = TLS1_1_VERSION;
7702
            break;
7703
#endif
7704
#ifndef WOLFSSL_NO_TLS12
7705
        case TLSv1_2_MINOR:
7706
            ret = TLS1_2_VERSION;
7707
            break;
7708
#endif
7709
#ifdef WOLFSSL_TLS13
7710
        case TLSv1_3_MINOR:
7711
            ret = TLS1_3_VERSION;
7712
            break;
7713
#endif
7714
        default:
7715
            ret = 0;
7716
            break;
7717
    }
7718
7719
    return ret;
7720
}
7721
7722
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
7723
{
7724
    int ret = 0;
7725
7726
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
7727
7728
    if (ctx != NULL) {
7729
        if (ctx->minProto) {
7730
            ret = 0;
7731
        }
7732
        else {
7733
            ret = GetMinProtoVersion(ctx->minDowngrade);
7734
        }
7735
    }
7736
    else {
7737
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
7738
    }
7739
7740
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
7741
7742
    return ret;
7743
}
7744
7745
7746
/* returns the maximum allowed protocol version given the 'options' used
7747
 * returns WOLFSSL_FATAL_ERROR on no match */
7748
static int GetMaxProtoVersion(long options)
7749
{
7750
#ifndef NO_TLS
7751
#ifdef WOLFSSL_TLS13
7752
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
7753
        return TLS1_3_VERSION;
7754
#endif
7755
#ifndef WOLFSSL_NO_TLS12
7756
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
7757
        return TLS1_2_VERSION;
7758
#endif
7759
#ifndef NO_OLD_TLS
7760
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
7761
        return TLS1_1_VERSION;
7762
    #ifdef WOLFSSL_ALLOW_TLSV10
7763
    if (!(options & WOLFSSL_OP_NO_TLSv1))
7764
        return TLS1_VERSION;
7765
    #endif
7766
    #ifdef WOLFSSL_ALLOW_SSLV3
7767
    if (!(options & WOLFSSL_OP_NO_SSLv3))
7768
        return SSL3_VERSION;
7769
    #endif
7770
#endif
7771
#else
7772
    (void)options;
7773
#endif /* NO_TLS */
7774
    return WOLFSSL_FATAL_ERROR;
7775
}
7776
7777
7778
/* returns the maximum protocol version for 'ctx' */
7779
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
7780
{
7781
    int ret = 0;
7782
    long options = 0; /* default to nothing set */
7783
7784
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
7785
7786
    if (ctx != NULL) {
7787
        options = wolfSSL_CTX_get_options(ctx);
7788
    }
7789
7790
    if ((ctx != NULL) && ctx->maxProto) {
7791
        ret = 0;
7792
    }
7793
    else {
7794
        ret = GetMaxProtoVersion(options);
7795
    }
7796
7797
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
7798
7799
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
7800
        WOLFSSL_MSG("Error getting max proto version");
7801
        ret = 0; /* setting ret to 0 to match compat return */
7802
    }
7803
    return ret;
7804
}
7805
#endif /* OPENSSL_EXTRA */
7806
7807
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
7808
    defined(HAVE_SECRET_CALLBACK)
7809
#if !defined(NO_WOLFSSL_CLIENT)
7810
/* Return the amount of random bytes copied over or error case.
7811
 * ssl : ssl struct after handshake
7812
 * out : buffer to hold random bytes
7813
 * outSz : either 0 (return max buffer sz) or size of out buffer
7814
 */
7815
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
7816
                                                                   size_t outSz)
7817
{
7818
    size_t size;
7819
7820
    /* return max size of buffer */
7821
    if (outSz == 0) {
7822
        return RAN_LEN;
7823
    }
7824
7825
    if (ssl == NULL || out == NULL) {
7826
        return 0;
7827
    }
7828
7829
    if (ssl->arrays == NULL) {
7830
        WOLFSSL_MSG("Arrays struct not saved after handshake");
7831
        return 0;
7832
    }
7833
7834
    if (outSz > RAN_LEN) {
7835
        size = RAN_LEN;
7836
    }
7837
    else {
7838
        size = outSz;
7839
    }
7840
7841
    XMEMCPY(out, ssl->arrays->clientRandom, size);
7842
    return size;
7843
}
7844
#endif /* !NO_WOLFSSL_CLIENT */
7845
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
7846
7847
#ifdef OPENSSL_EXTRA
7848
7849
    unsigned long wolfSSLeay(void)
7850
    {
7851
#ifdef SSLEAY_VERSION_NUMBER
7852
        return SSLEAY_VERSION_NUMBER;
7853
#else
7854
        return OPENSSL_VERSION_NUMBER;
7855
#endif
7856
    }
7857
7858
    unsigned long wolfSSL_OpenSSL_version_num(void)
7859
    {
7860
        return OPENSSL_VERSION_NUMBER;
7861
    }
7862
7863
    const char* wolfSSLeay_version(int type)
7864
    {
7865
        (void)type;
7866
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
7867
        return wolfSSL_OpenSSL_version(type);
7868
#else
7869
        return wolfSSL_OpenSSL_version();
7870
#endif
7871
    }
7872
#endif /* OPENSSL_EXTRA */
7873
7874
#ifdef OPENSSL_EXTRA
7875
    void wolfSSL_ERR_free_strings(void)
7876
    {
7877
        /* handled internally */
7878
    }
7879
7880
    void wolfSSL_cleanup_all_ex_data(void)
7881
    {
7882
        /* nothing to do here */
7883
    }
7884
7885
#endif /* OPENSSL_EXTRA */
7886
7887
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
7888
    defined(HAVE_CURL)
7889
    void wolfSSL_ERR_clear_error(void)
7890
    {
7891
        WOLFSSL_ENTER("wolfSSL_ERR_clear_error");
7892
    #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
7893
        wc_ClearErrorNodes();
7894
    #endif
7895
    }
7896
#endif
7897
7898
    int wolfSSL_clear(WOLFSSL* ssl)
7899
0
    {
7900
0
        WOLFSSL_ENTER("wolfSSL_clear");
7901
7902
0
        if (ssl == NULL) {
7903
0
            return WOLFSSL_FAILURE;
7904
0
        }
7905
7906
0
        if (!ssl->options.handShakeDone) {
7907
            /* Only reset the session if we didn't complete a handshake */
7908
0
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
7909
0
            ssl->session = wolfSSL_NewSession(ssl->heap);
7910
0
            if (ssl->session == NULL) {
7911
0
                return WOLFSSL_FAILURE;
7912
0
            }
7913
0
        }
7914
7915
        /* reset error */
7916
0
        ssl->error = 0;
7917
7918
        /* reset option bits */
7919
0
        ssl->options.isClosed = 0;
7920
0
        ssl->options.connReset = 0;
7921
0
        ssl->options.sentNotify = 0;
7922
0
        ssl->options.closeNotify = 0;
7923
0
        ssl->options.sendVerify = 0;
7924
0
        ssl->options.serverState = NULL_STATE;
7925
0
        ssl->options.clientState = NULL_STATE;
7926
0
        ssl->options.connectState = CONNECT_BEGIN;
7927
0
        ssl->options.acceptState  = ACCEPT_BEGIN;
7928
0
        ssl->options.handShakeState  = NULL_STATE;
7929
0
        ssl->options.handShakeDone = 0;
7930
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
7931
        /* A per-certificate yield (WOLFSSL_ASYNC_CERT_YIELD) sets this and it is
7932
         * normally cleared on the next ProcessPeerCerts re-entry. Clear it here
7933
         * so reusing this object after abandoning a yielded handshake cannot
7934
         * skip the ProcessPeerCerts state reset on the next fresh entry. */
7935
        ssl->options.certYieldPending = 0;
7936
#endif
7937
0
        ssl->recordSzOverhead = 0;
7938
0
        ssl->options.processReply = 0; /* doProcessInit */
7939
0
        ssl->options.havePeerVerify = 0;
7940
0
        ssl->options.havePeerCert = 0;
7941
0
        ssl->options.peerAuthGood = 0;
7942
0
        ssl->options.tls1_3 = 0;
7943
0
        ssl->options.haveSessionId = 0;
7944
0
        ssl->options.tls = 0;
7945
0
        ssl->options.tls1_1 = 0;
7946
0
    #ifdef WOLFSSL_TLS13
7947
    #ifdef WOLFSSL_SEND_HRR_COOKIE
7948
        ssl->options.hrrSentCookie = 0;
7949
    #endif
7950
0
        ssl->options.hrrSentKeyShare = 0;
7951
0
    #endif
7952
    #ifdef WOLFSSL_DTLS
7953
        ssl->options.dtlsStateful = 0;
7954
    #endif
7955
0
    #ifdef WOLFSSL_TLS13
7956
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
7957
        ssl->options.noPskDheKe = ssl->ctx->noPskDheKe;
7958
        #ifdef HAVE_SUPPORTED_CURVES
7959
        ssl->options.onlyPskDheKe = ssl->ctx->onlyPskDheKe;
7960
        #endif
7961
    #endif
7962
0
    #endif
7963
    #ifdef HAVE_SESSION_TICKET
7964
        #ifdef WOLFSSL_TLS13
7965
        ssl->options.ticketsSent = 0;
7966
        #endif
7967
        ssl->options.rejectTicket = 0;
7968
    #endif
7969
    #ifdef WOLFSSL_EARLY_DATA
7970
        ssl->earlyData = no_early_data;
7971
        ssl->earlyDataSz = 0;
7972
    #endif
7973
7974
0
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
7975
0
        TLSX_FreeAll(ssl->extensions, ssl->heap);
7976
0
        ssl->extensions = NULL;
7977
0
      #if defined(HAVE_SECURE_RENEGOTIATION) \
7978
0
       || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7979
0
        ssl->secure_renegotiation = NULL;
7980
0
      #endif
7981
0
    #endif
7982
7983
0
        if (ssl->keys.encryptionOn) {
7984
0
            ForceZero(ssl->buffers.inputBuffer.buffer -
7985
0
                ssl->buffers.inputBuffer.offset,
7986
0
                ssl->buffers.inputBuffer.bufferSize);
7987
        #ifdef WOLFSSL_CHECK_MEM_ZERO
7988
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
7989
                ssl->buffers.inputBuffer.offset,
7990
                ssl->buffers.inputBuffer.bufferSize);
7991
        #endif
7992
0
        }
7993
0
        ssl->keys.encryptionOn = 0;
7994
0
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
7995
7996
        /* Discard any partial handshake-message reassembly on reuse. */
7997
0
        XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
7998
0
        ssl->pendingMsg = NULL;
7999
0
        ssl->pendingMsgSz = 0;
8000
0
        ssl->pendingMsgOffset = 0;
8001
0
        ssl->pendingMsgType = 0;
8002
8003
0
        FreeCiphers(ssl);
8004
0
        InitCiphers(ssl);
8005
0
        InitCipherSpecs(&ssl->specs);
8006
8007
0
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
8008
0
            return WOLFSSL_FAILURE;
8009
8010
0
        if (InitHandshakeHashes(ssl) != 0)
8011
0
            return WOLFSSL_FAILURE;
8012
8013
#ifdef KEEP_PEER_CERT
8014
        FreeX509(&ssl->peerCert);
8015
        InitX509(&ssl->peerCert, 0, ssl->heap);
8016
#endif
8017
8018
#ifdef WOLFSSL_QUIC
8019
        wolfSSL_quic_clear(ssl);
8020
#endif
8021
#ifdef HAVE_OCSP
8022
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
8023
        ssl->response_idx = 0;
8024
#endif
8025
#endif
8026
0
        return WOLFSSL_SUCCESS;
8027
0
    }
8028
8029
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
8030
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
8031
    {
8032
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
8033
8034
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
8035
        switch(mode) {
8036
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
8037
                ctx->partialWrite = 1;
8038
                break;
8039
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8040
            case SSL_MODE_RELEASE_BUFFERS:
8041
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
8042
                break;
8043
            #endif
8044
            case WOLFSSL_MODE_AUTO_RETRY:
8045
                ctx->autoRetry = 1;
8046
                break;
8047
            default:
8048
                WOLFSSL_MSG("Mode Not Implemented");
8049
        }
8050
8051
        /* WOLFSSL_MODE_AUTO_RETRY
8052
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
8053
8054
        return mode;
8055
    }
8056
8057
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
8058
    {
8059
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
8060
8061
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
8062
        switch(mode) {
8063
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
8064
                ctx->partialWrite = 0;
8065
                break;
8066
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8067
            case SSL_MODE_RELEASE_BUFFERS:
8068
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
8069
                break;
8070
            #endif
8071
            case WOLFSSL_MODE_AUTO_RETRY:
8072
                ctx->autoRetry = 0;
8073
                break;
8074
            default:
8075
                WOLFSSL_MSG("Mode Not Implemented");
8076
        }
8077
8078
        /* WOLFSSL_MODE_AUTO_RETRY
8079
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
8080
8081
        return 0;
8082
    }
8083
#endif
8084
8085
#ifdef OPENSSL_EXTRA
8086
8087
    #ifndef NO_WOLFSSL_STUB
8088
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
8089
    {
8090
        /* TODO: */
8091
        (void)ssl;
8092
        WOLFSSL_STUB("SSL_get_mode");
8093
        return 0;
8094
    }
8095
    #endif
8096
8097
    #ifndef NO_WOLFSSL_STUB
8098
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
8099
    {
8100
        /* TODO: */
8101
        (void)ctx;
8102
        WOLFSSL_STUB("SSL_CTX_get_mode");
8103
        return 0;
8104
    }
8105
    #endif
8106
8107
    #ifndef NO_WOLFSSL_STUB
8108
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
8109
    {
8110
        /* TODO: maybe? */
8111
        (void)ctx;
8112
        (void)m;
8113
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
8114
    }
8115
    #endif
8116
8117
8118
    /* returns the unsigned error value and increments the pointer into the
8119
     * error queue.
8120
     *
8121
     * file  pointer to file name
8122
     * line  gets set to line number of error when not NULL
8123
     */
8124
    unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line)
8125
    {
8126
    #ifdef WOLFSSL_HAVE_ERROR_QUEUE
8127
        int ret = wc_PullErrorNode(file, NULL, line);
8128
        if (ret < 0) {
8129
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
8130
                return 0; /* no errors in queue */
8131
            WOLFSSL_MSG("Issue getting error node");
8132
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret);
8133
            ret = 0 - ret; /* return absolute value of error */
8134
8135
            /* panic and try to clear out nodes */
8136
            wc_ClearErrorNodes();
8137
        }
8138
        return (unsigned long)ret;
8139
    #else
8140
        (void)file;
8141
        (void)line;
8142
8143
        return 0;
8144
    #endif
8145
    }
8146
8147
8148
#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \
8149
    (!defined(_WIN32) && !defined(NO_ERROR_QUEUE))
8150
    static const char WOLFSSL_SYS_ACCEPT_T[]  = "accept";
8151
    static const char WOLFSSL_SYS_BIND_T[]    = "bind";
8152
    static const char WOLFSSL_SYS_CONNECT_T[] = "connect";
8153
    static const char WOLFSSL_SYS_FOPEN_T[]   = "fopen";
8154
    static const char WOLFSSL_SYS_FREAD_T[]   = "fread";
8155
    static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo";
8156
    static const char WOLFSSL_SYS_GETSOCKOPT_T[]  = "getsockopt";
8157
    static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname";
8158
    static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname";
8159
    static const char WOLFSSL_SYS_GETNAMEINFO_T[]   = "getnameinfo";
8160
    static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname";
8161
    static const char WOLFSSL_SYS_IOCTLSOCKET_T[]   = "ioctlsocket";
8162
    static const char WOLFSSL_SYS_LISTEN_T[]        = "listen";
8163
    static const char WOLFSSL_SYS_OPENDIR_T[]       = "opendir";
8164
    static const char WOLFSSL_SYS_SETSOCKOPT_T[]    = "setsockopt";
8165
    static const char WOLFSSL_SYS_SOCKET_T[]        = "socket";
8166
8167
    /* switch with int mapped to function name for compatibility */
8168
    static const char* wolfSSL_ERR_sys_func(int fun)
8169
    {
8170
        switch (fun) {
8171
            case WOLFSSL_SYS_ACCEPT:      return WOLFSSL_SYS_ACCEPT_T;
8172
            case WOLFSSL_SYS_BIND:        return WOLFSSL_SYS_BIND_T;
8173
            case WOLFSSL_SYS_CONNECT:     return WOLFSSL_SYS_CONNECT_T;
8174
            case WOLFSSL_SYS_FOPEN:       return WOLFSSL_SYS_FOPEN_T;
8175
            case WOLFSSL_SYS_FREAD:       return WOLFSSL_SYS_FREAD_T;
8176
            case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T;
8177
            case WOLFSSL_SYS_GETSOCKOPT:  return WOLFSSL_SYS_GETSOCKOPT_T;
8178
            case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T;
8179
            case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T;
8180
            case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T;
8181
            case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T;
8182
            case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T;
8183
            case WOLFSSL_SYS_LISTEN:      return WOLFSSL_SYS_LISTEN_T;
8184
            case WOLFSSL_SYS_OPENDIR:     return WOLFSSL_SYS_OPENDIR_T;
8185
            case WOLFSSL_SYS_SETSOCKOPT:  return WOLFSSL_SYS_SETSOCKOPT_T;
8186
            case WOLFSSL_SYS_SOCKET:      return WOLFSSL_SYS_SOCKET_T;
8187
            default:
8188
                return "NULL";
8189
        }
8190
    }
8191
#endif /* DEBUG_WOLFSSL */
8192
8193
8194
    void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file,
8195
            int line)
8196
    {
8197
        WOLFSSL_ENTER("wolfSSL_ERR_put_error");
8198
8199
        #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA)
8200
        (void)fun;
8201
        (void)err;
8202
        (void)file;
8203
        (void)line;
8204
        WOLFSSL_MSG("Not compiled in debug mode");
8205
        #elif defined(OPENSSL_EXTRA) && \
8206
                (defined(_WIN32) || defined(NO_ERROR_QUEUE))
8207
        (void)fun;
8208
        (void)file;
8209
        (void)line;
8210
        WOLFSSL_ERROR(err);
8211
        #else
8212
        WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line,
8213
            file, NULL);
8214
        #endif
8215
        (void)lib;
8216
    }
8217
8218
8219
    /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for
8220
     * more flexibility.
8221
     *
8222
     * file  output pointer to file where error happened
8223
     * line  output to line number of error
8224
     * data  output data. Is a string if WOLFSSL_ERR_TXT_STRING flag is used
8225
     * flags output format of output
8226
     *
8227
     * Returns the error value or 0 if no errors are in the queue
8228
     */
8229
    unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line,
8230
                                                  const char** data, int *flags)
8231
    {
8232
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
8233
        int ret;
8234
8235
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
8236
8237
        if (flags != NULL)
8238
            *flags = WOLFSSL_ERR_TXT_STRING; /* Clear the flags */
8239
8240
        ret = wc_PullErrorNode(file, data, line);
8241
        if (ret < 0) {
8242
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
8243
                return 0; /* no errors in queue */
8244
            WOLFSSL_MSG("Error with pulling error node!");
8245
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret);
8246
            ret = 0 - ret; /* return absolute value of error */
8247
8248
            /* panic and try to clear out nodes */
8249
            wc_ClearErrorNodes();
8250
        }
8251
8252
        return (unsigned long)ret;
8253
#else
8254
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
8255
        WOLFSSL_MSG("Error queue turned off, can not get error line");
8256
        (void)file;
8257
        (void)line;
8258
        (void)data;
8259
        (void)flags;
8260
        return 0;
8261
#endif
8262
    }
8263
8264
#endif /* OPENSSL_EXTRA */
8265
8266
8267
#ifdef SESSION_CERTS
8268
    /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object.
8269
     *
8270
     * x509  WOLFSSL_X509 object to decode into.
8271
     * in    X509 DER data.
8272
     * len   Length of the X509 DER data.
8273
     * returns the new certificate on success, otherwise NULL.
8274
     */
8275
    static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len)
8276
    {
8277
        int          ret;
8278
        WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
8279
        if (x509 == NULL || in == NULL || len <= 0)
8280
            return BAD_FUNC_ARG;
8281
8282
        WC_ALLOC_VAR_EX(cert, DecodedCert, 1, NULL, DYNAMIC_TYPE_DCERT,
8283
            return MEMORY_E);
8284
8285
        /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object.
8286
         */
8287
        InitDecodedCert(cert, (byte*)in, (word32)len, NULL);
8288
        if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) == 0) {
8289
        /* Check if x509 was not previously initialized by wolfSSL_X509_new() */
8290
            if (x509->dynamicMemory != TRUE)
8291
                InitX509(x509, 0, NULL);
8292
            ret = CopyDecodedToX509(x509, cert);
8293
        }
8294
        FreeDecodedCert(cert);
8295
        WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
8296
8297
        return ret;
8298
    }
8299
#endif /* SESSION_CERTS */
8300
8301
8302
#ifdef KEEP_PEER_CERT
8303
    WOLFSSL_ABI
8304
    WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl)
8305
    {
8306
        WOLFSSL_X509* ret = NULL;
8307
        WOLFSSL_ENTER("wolfSSL_get_peer_certificate");
8308
        if (ssl != NULL) {
8309
            if (ssl->peerCert.issuer.sz)
8310
                ret = wolfSSL_X509_dup(&ssl->peerCert);
8311
#ifdef SESSION_CERTS
8312
            else if (ssl->session->chain.count > 0) {
8313
                if (DecodeToX509(&ssl->peerCert,
8314
                        ssl->session->chain.certs[0].buffer,
8315
                        ssl->session->chain.certs[0].length) == 0) {
8316
                    ret = wolfSSL_X509_dup(&ssl->peerCert);
8317
                }
8318
            }
8319
#endif
8320
        }
8321
        WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL);
8322
        return ret;
8323
    }
8324
8325
#endif /* KEEP_PEER_CERT */
8326
8327
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
8328
/* Return stack of peer certs.
8329
 * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl
8330
 * is.
8331
 */
8332
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl)
8333
{
8334
    WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain");
8335
8336
    if (ssl == NULL)
8337
        return NULL;
8338
8339
    /* Try to populate if NULL or empty */
8340
    if (ssl->peerCertChain == NULL ||
8341
            wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) {
8342
        wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl);
8343
    }
8344
    return ssl->peerCertChain;
8345
}
8346
8347
8348
static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
8349
        WOLFSSL_X509 *x);
8350
/**
8351
 * Recursively push the issuer CA chain onto the stack
8352
 * @param cm The cert manager that is queried for the issuer
8353
 * @param x  This cert's issuer will be queried in cm
8354
 * @param sk The issuer is pushed onto this stack
8355
 * @return 0 on success or no issuer found
8356
 *         WOLFSSL_FATAL_ERROR on a fatal error
8357
 */
8358
static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm,
8359
        WOLFSSL_X509 *x, WOLFSSL_STACK* sk)
8360
{
8361
    int i;
8362
    for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
8363
        WOLFSSL_X509* issuer = NULL;
8364
        if (x509GetIssuerFromCM(&issuer, cm, x) != WOLFSSL_SUCCESS)
8365
            break;
8366
        if (wolfSSL_sk_X509_push(sk, issuer) <= 0) {
8367
            wolfSSL_X509_free(issuer);
8368
            issuer = NULL;
8369
            return WOLFSSL_FATAL_ERROR;
8370
        }
8371
        x = issuer;
8372
    }
8373
    return 0;
8374
}
8375
8376
8377
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
8378
    or ssl->verifiedChain based off of the ssl session chain. Attempts to place
8379
    CA certificates at the bottom of the stack for a verified chain. Returns
8380
    stack of WOLFSSL_X509 certs or NULL on failure */
8381
static WOLF_STACK_OF(WOLFSSL_X509)* CreatePeerCertChain(const WOLFSSL* ssl,
8382
    int verifiedFlag)
8383
{
8384
    WOLFSSL_STACK* sk;
8385
    WOLFSSL_X509* x509;
8386
    int i = 0;
8387
    int err;
8388
8389
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
8390
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
8391
        return NULL;
8392
8393
    sk = wolfSSL_sk_X509_new_null();
8394
    for (i = 0; i < ssl->session->chain.count; i++) {
8395
        x509 = wolfSSL_X509_new_ex(ssl->heap);
8396
        if (x509 == NULL) {
8397
            WOLFSSL_MSG("Error Creating X509");
8398
            wolfSSL_sk_X509_pop_free(sk, NULL);
8399
            return NULL;
8400
        }
8401
        err = DecodeToX509(x509, ssl->session->chain.certs[i].buffer,
8402
                             ssl->session->chain.certs[i].length);
8403
        if (err == 0 && wolfSSL_sk_X509_push(sk, x509) <= 0)
8404
            err = WOLFSSL_FATAL_ERROR;
8405
        if (err == 0 && i == ssl->session->chain.count-1 && verifiedFlag) {
8406
            /* On the last element in the verified chain try to add the CA chain
8407
             * if we have one for this cert */
8408
            SSL_CM_WARNING(ssl);
8409
            err = PushCAx509Chain(SSL_CM(ssl), x509, sk);
8410
        }
8411
        if (err != 0) {
8412
            WOLFSSL_MSG("Error decoding cert");
8413
            wolfSSL_X509_free(x509);
8414
            x509 = NULL;
8415
            wolfSSL_sk_X509_pop_free(sk, NULL);
8416
            return NULL;
8417
        }
8418
    }
8419
8420
    if (sk == NULL) {
8421
        WOLFSSL_MSG("Null session chain");
8422
    }
8423
    return sk;
8424
}
8425
8426
8427
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
8428
    returns the stack on success and NULL on failure */
8429
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl)
8430
{
8431
    WOLFSSL_STACK* sk;
8432
8433
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
8434
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
8435
        return NULL;
8436
8437
    sk = CreatePeerCertChain(ssl, 0);
8438
8439
    if (sk != NULL) {
8440
        if (ssl->options.side == WOLFSSL_SERVER_END) {
8441
            if (ssl->session->peer)
8442
                wolfSSL_X509_free(ssl->session->peer);
8443
8444
            ssl->session->peer = wolfSSL_sk_X509_shift(sk);
8445
            ssl->session->peerVerifyRet = ssl->peerVerifyRet;
8446
        }
8447
        if (ssl->peerCertChain != NULL)
8448
            wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
8449
        /* This is Free'd when ssl is Free'd */
8450
        ssl->peerCertChain = sk;
8451
    }
8452
    return sk;
8453
}
8454
8455
#ifdef KEEP_PEER_CERT
8456
/**
8457
 * Implemented in a similar way that ngx_ssl_ocsp_validate does it when
8458
 * SSL_get0_verified_chain is not available.
8459
 * @param ssl WOLFSSL object to extract certs from
8460
 * @return Stack of verified certs
8461
 */
8462
WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl)
8463
{
8464
    WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL;
8465
    WOLFSSL_X509_STORE_CTX* storeCtx = NULL;
8466
    WOLFSSL_X509* peerCert = NULL;
8467
8468
    WOLFSSL_ENTER("wolfSSL_get0_verified_chain");
8469
8470
    if (ssl == NULL || ssl->ctx == NULL) {
8471
        WOLFSSL_MSG("Bad parameter");
8472
        return NULL;
8473
    }
8474
8475
    peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl);
8476
    if (peerCert == NULL) {
8477
        WOLFSSL_MSG("wolfSSL_get_peer_certificate error");
8478
        return NULL;
8479
    }
8480
    /* wolfSSL_get_peer_certificate returns a copy. We want the internal
8481
     * member so that we don't have to worry about free'ing it. We call
8482
     * wolfSSL_get_peer_certificate so that we don't have to worry about
8483
     * setting up the internal pointer. */
8484
    wolfSSL_X509_free(peerCert);
8485
    peerCert = (WOLFSSL_X509*)&ssl->peerCert;
8486
    chain = CreatePeerCertChain((WOLFSSL*)ssl, 1);
8487
    if (chain == NULL) {
8488
        WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error");
8489
        return NULL;
8490
    }
8491
8492
    if (ssl->verifiedChain != NULL) {
8493
        wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL);
8494
    }
8495
    ((WOLFSSL*)ssl)->verifiedChain = chain;
8496
8497
    storeCtx = wolfSSL_X509_STORE_CTX_new();
8498
    if (storeCtx == NULL) {
8499
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error");
8500
        return NULL;
8501
    }
8502
    if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl),
8503
            peerCert, chain) != WOLFSSL_SUCCESS) {
8504
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error");
8505
        wolfSSL_X509_STORE_CTX_free(storeCtx);
8506
        return NULL;
8507
    }
8508
    if (wolfSSL_X509_verify_cert(storeCtx) <= 0) {
8509
        WOLFSSL_MSG("wolfSSL_X509_verify_cert error");
8510
        wolfSSL_X509_STORE_CTX_free(storeCtx);
8511
        return NULL;
8512
    }
8513
    wolfSSL_X509_STORE_CTX_free(storeCtx);
8514
    return chain;
8515
}
8516
#endif /* KEEP_PEER_CERT */
8517
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
8518
8519
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8520
void wolfSSL_set_connect_state(WOLFSSL* ssl)
8521
{
8522
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
8523
    if (ssl == NULL) {
8524
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
8525
        return;
8526
    }
8527
8528
    #ifndef NO_DH
8529
    /* client creates its own DH parameters on handshake */
8530
    if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
8531
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
8532
            DYNAMIC_TYPE_PUBLIC_KEY);
8533
    }
8534
    ssl->buffers.serverDH_P.buffer = NULL;
8535
    if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
8536
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
8537
            DYNAMIC_TYPE_PUBLIC_KEY);
8538
    }
8539
    ssl->buffers.serverDH_G.buffer = NULL;
8540
    #endif
8541
8542
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
8543
        WOLFSSL_MSG("Error initializing client side");
8544
    }
8545
}
8546
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
8547
8548
8549
int wolfSSL_get_shutdown(const WOLFSSL* ssl)
8550
0
{
8551
0
    int isShutdown = 0;
8552
8553
0
    WOLFSSL_ENTER("wolfSSL_get_shutdown");
8554
8555
0
    if (ssl) {
8556
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8557
        if (ssl->options.shutdownDone) {
8558
            /* The SSL object was possibly cleared with wolfSSL_clear after
8559
             * a successful shutdown. Simulate a response for a full
8560
             * bidirectional shutdown. */
8561
            isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN;
8562
        }
8563
        else
8564
#endif
8565
0
        {
8566
            /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent   *
8567
             * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */
8568
0
            if (ssl->options.sentNotify)
8569
0
                isShutdown |= WOLFSSL_SENT_SHUTDOWN;
8570
0
            if (ssl->options.closeNotify||ssl->options.connReset)
8571
0
                isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN;
8572
0
        }
8573
8574
0
    }
8575
8576
0
    WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown);
8577
0
    return isShutdown;
8578
0
}
8579
8580
8581
int wolfSSL_session_reused(WOLFSSL* ssl)
8582
0
{
8583
0
    int resuming = 0;
8584
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
8585
0
    if (ssl) {
8586
0
#ifndef HAVE_SECURE_RENEGOTIATION
8587
0
        resuming = ssl->options.resuming;
8588
#else
8589
        resuming = ssl->options.resuming || ssl->options.resumed;
8590
#endif
8591
0
    }
8592
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
8593
0
    return resuming;
8594
0
}
8595
8596
/* helper function that takes in a protocol version struct and returns string */
8597
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
8598
0
{
8599
0
    WOLFSSL_ENTER("wolfSSL_get_version");
8600
8601
0
    if (version == NULL) {
8602
0
        return "Bad arg";
8603
0
    }
8604
8605
0
    if (version->major == SSLv3_MAJOR) {
8606
0
        switch (version->minor) {
8607
0
            case SSLv3_MINOR :
8608
0
                return "SSLv3";
8609
0
            case TLSv1_MINOR :
8610
0
                return "TLSv1";
8611
0
            case TLSv1_1_MINOR :
8612
0
                return "TLSv1.1";
8613
0
            case TLSv1_2_MINOR :
8614
0
                return "TLSv1.2";
8615
0
            case TLSv1_3_MINOR :
8616
0
                return "TLSv1.3";
8617
0
            default:
8618
0
                return "unknown";
8619
0
        }
8620
0
    }
8621
#ifdef WOLFSSL_DTLS
8622
    else if (version->major == DTLS_MAJOR) {
8623
        switch (version->minor) {
8624
            case DTLS_MINOR :
8625
                return "DTLS";
8626
            case DTLSv1_2_MINOR :
8627
                return "DTLSv1.2";
8628
            case DTLSv1_3_MINOR :
8629
                return "DTLSv1.3";
8630
            default:
8631
                return "unknown";
8632
        }
8633
    }
8634
#endif /* WOLFSSL_DTLS */
8635
0
    return "unknown";
8636
0
}
8637
8638
8639
const char* wolfSSL_get_version(const WOLFSSL* ssl)
8640
0
{
8641
0
    if (ssl == NULL) {
8642
0
        WOLFSSL_MSG("Bad argument");
8643
0
        return "unknown";
8644
0
    }
8645
8646
0
    return wolfSSL_internal_get_version(&ssl->version);
8647
0
}
8648
8649
8650
/* current library version */
8651
const char* wolfSSL_lib_version(void)
8652
0
{
8653
0
    return LIBWOLFSSL_VERSION_STRING;
8654
0
}
8655
8656
#ifdef OPENSSL_EXTRA
8657
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
8658
const char* wolfSSL_OpenSSL_version(int a)
8659
{
8660
    (void)a;
8661
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
8662
}
8663
#else
8664
const char* wolfSSL_OpenSSL_version(void)
8665
{
8666
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
8667
}
8668
#endif /* WOLFSSL_QT */
8669
#endif
8670
8671
8672
/* current library version in hex */
8673
word32 wolfSSL_lib_version_hex(void)
8674
0
{
8675
0
    return LIBWOLFSSL_VERSION_HEX;
8676
0
}
8677
8678
8679
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
8680
0
{
8681
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
8682
0
    if (ssl)
8683
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
8684
0
    return 0;
8685
0
}
8686
8687
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
8688
0
{
8689
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
8690
0
    if (ssl) {
8691
0
        ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
8692
0
        ssl->cipher.cipherSuite  = ssl->options.cipherSuite;
8693
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8694
        ssl->cipher.bits = ssl->specs.key_size * 8;
8695
#endif
8696
0
        return &ssl->cipher;
8697
0
    }
8698
0
    else
8699
0
        return NULL;
8700
0
}
8701
8702
8703
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
8704
0
{
8705
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
8706
8707
0
    if (cipher == NULL) {
8708
0
        return NULL;
8709
0
    }
8710
8711
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
8712
0
        !defined(WOLFSSL_QT)
8713
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
8714
    #else
8715
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
8716
                cipher->cipherSuite);
8717
    #endif
8718
0
}
8719
8720
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
8721
0
{
8722
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
8723
8724
0
    if (cipher == NULL || cipher->ssl == NULL) {
8725
0
        return NULL;
8726
0
    }
8727
8728
0
    return wolfSSL_get_version(cipher->ssl);
8729
0
}
8730
8731
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
8732
0
{
8733
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
8734
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
8735
0
}
8736
8737
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
8738
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
8739
0
{
8740
    /* get access to cipher_name_idx in internal.c */
8741
0
    return wolfSSL_get_cipher_name_internal(ssl);
8742
0
}
8743
8744
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
8745
    byte cipherSuite)
8746
0
{
8747
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
8748
0
}
8749
8750
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
8751
        byte cipherSuite)
8752
0
{
8753
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
8754
0
}
8755
8756
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
8757
0
                                       byte* cipherSuite, int *flags) {
8758
0
    if ((name == NULL) ||
8759
0
        (cipherSuite0 == NULL) ||
8760
0
        (cipherSuite == NULL) ||
8761
0
        (flags == NULL))
8762
0
        return BAD_FUNC_ARG;
8763
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
8764
0
                                  flags);
8765
0
}
8766
8767
8768
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
8769
0
{
8770
0
    word16 cipher_id = 0;
8771
8772
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
8773
8774
0
    if (cipher && cipher->ssl) {
8775
0
        cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) |
8776
0
                     cipher->ssl->options.cipherSuite;
8777
0
    }
8778
8779
0
    return cipher_id;
8780
0
}
8781
8782
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
8783
0
{
8784
0
    const WOLFSSL_CIPHER* cipher = NULL;
8785
0
    byte cipherSuite0, cipherSuite;
8786
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
8787
8788
    /* extract cipher id information */
8789
0
    cipherSuite =   (value       & 0xFF);
8790
0
    cipherSuite0 = ((value >> 8) & 0xFF);
8791
8792
    /* TODO: lookup by cipherSuite0 / cipherSuite */
8793
0
    (void)cipherSuite0;
8794
0
    (void)cipherSuite;
8795
8796
0
    return cipher;
8797
0
}
8798
8799
8800
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
8801
    !defined(NO_DH) || (defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM))
8802
#ifdef HAVE_FFDHE
8803
static const char* wolfssl_ffdhe_name(word16 group)
8804
0
{
8805
0
    const char* str = NULL;
8806
0
    switch (group) {
8807
0
        case WOLFSSL_FFDHE_2048:
8808
0
            str = "FFDHE_2048";
8809
0
            break;
8810
0
        case WOLFSSL_FFDHE_3072:
8811
0
            str = "FFDHE_3072";
8812
0
            break;
8813
0
        case WOLFSSL_FFDHE_4096:
8814
0
            str = "FFDHE_4096";
8815
0
            break;
8816
0
        case WOLFSSL_FFDHE_6144:
8817
0
            str = "FFDHE_6144";
8818
0
            break;
8819
0
        case WOLFSSL_FFDHE_8192:
8820
0
            str = "FFDHE_8192";
8821
0
            break;
8822
0
        default:
8823
0
            break;
8824
0
    }
8825
0
    return str;
8826
0
}
8827
#endif
8828
/* Return the name of the curve used for key exchange as a printable string.
8829
 *
8830
 * ssl  The SSL/TLS object.
8831
 * returns NULL if ECDH was not used, otherwise the name as a string.
8832
 */
8833
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
8834
0
{
8835
0
    const char* cName = NULL;
8836
8837
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
8838
8839
0
    if (ssl == NULL)
8840
0
        return NULL;
8841
8842
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
8843
    /* Check for post-quantum groups. Return now because we do not want the ECC
8844
     * check to override this result in the case of a hybrid. */
8845
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
8846
0
        switch (ssl->namedGroup) {
8847
0
#ifndef WOLFSSL_NO_ML_KEM
8848
0
    #ifndef WOLFSSL_NO_ML_KEM_512
8849
0
        case WOLFSSL_ML_KEM_512:
8850
0
            return "ML_KEM_512";
8851
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8852
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8853
        case WOLFSSL_P256_ML_KEM_512_OLD:
8854
            return "P256_ML_KEM_512_OLD";
8855
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8856
        case WOLFSSL_SECP256R1MLKEM512:
8857
            return "SecP256r1MLKEM512";
8858
        #ifdef HAVE_CURVE25519
8859
        case WOLFSSL_X25519MLKEM512:
8860
            return "X25519MLKEM512";
8861
        #endif /* HAVE_CURVE25519 */
8862
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8863
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
8864
0
    #ifndef WOLFSSL_NO_ML_KEM_768
8865
0
        case WOLFSSL_ML_KEM_768:
8866
0
            return "ML_KEM_768";
8867
0
        #ifdef WOLFSSL_PQC_HYBRIDS
8868
0
        case WOLFSSL_SECP256R1MLKEM768:
8869
0
            return "SecP256r1MLKEM768";
8870
        #ifdef HAVE_CURVE25519
8871
        case WOLFSSL_X25519MLKEM768:
8872
            return "X25519MLKEM768";
8873
        #endif
8874
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
8875
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8876
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8877
        case WOLFSSL_P384_ML_KEM_768_OLD:
8878
            return "P384_ML_KEM_768_OLD";
8879
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8880
        case WOLFSSL_SECP384R1MLKEM768:
8881
            return "SecP384r1MLKEM768";
8882
        #ifdef HAVE_CURVE448
8883
        case WOLFSSL_X448MLKEM768:
8884
            return "X448MLKEM768";
8885
        #endif /* HAVE_CURVE448 */
8886
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8887
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
8888
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
8889
0
        case WOLFSSL_ML_KEM_1024:
8890
0
            return "ML_KEM_1024";
8891
0
        #ifdef WOLFSSL_PQC_HYBRIDS
8892
0
        case WOLFSSL_SECP384R1MLKEM1024:
8893
0
            return "SecP384r1MLKEM1024";
8894
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
8895
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8896
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8897
        case WOLFSSL_P521_ML_KEM_1024_OLD:
8898
            return "P521_ML_KEM_1024_OLD";
8899
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8900
        case WOLFSSL_SECP521R1MLKEM1024:
8901
            return "SecP521r1MLKEM1024";
8902
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8903
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
8904
0
#endif /* WOLFSSL_NO_ML_KEM */
8905
#ifdef WOLFSSL_MLKEM_KYBER
8906
    #ifndef WOLFSSL_NO_KYBER512
8907
        case WOLFSSL_KYBER_LEVEL1:
8908
            return "KYBER_LEVEL1";
8909
        case WOLFSSL_P256_KYBER_LEVEL1:
8910
            return "P256_KYBER_LEVEL1";
8911
        #ifdef HAVE_CURVE25519
8912
        case WOLFSSL_X25519_KYBER_LEVEL1:
8913
            return "X25519_KYBER_LEVEL1";
8914
        #endif
8915
    #endif
8916
    #ifndef WOLFSSL_NO_KYBER768
8917
        case WOLFSSL_KYBER_LEVEL3:
8918
            return "KYBER_LEVEL3";
8919
        case WOLFSSL_P384_KYBER_LEVEL3:
8920
            return "P384_KYBER_LEVEL3";
8921
        case WOLFSSL_P256_KYBER_LEVEL3:
8922
            return "P256_KYBER_LEVEL3";
8923
        #ifdef HAVE_CURVE25519
8924
        case WOLFSSL_X25519_KYBER_LEVEL3:
8925
            return "X25519_KYBER_LEVEL3";
8926
        #endif
8927
        #ifdef HAVE_CURVE448
8928
        case WOLFSSL_X448_KYBER_LEVEL3:
8929
            return "X448_KYBER_LEVEL3";
8930
        #endif
8931
    #endif
8932
    #ifndef WOLFSSL_NO_KYBER1024
8933
        case WOLFSSL_KYBER_LEVEL5:
8934
            return "KYBER_LEVEL5";
8935
        case WOLFSSL_P521_KYBER_LEVEL5:
8936
            return "P521_KYBER_LEVEL5";
8937
    #endif
8938
#endif /* WOLFSSL_MLKEM_KYBER */
8939
0
        }
8940
0
    }
8941
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
8942
8943
0
#ifdef HAVE_FFDHE
8944
0
    if (ssl->namedGroup != 0) {
8945
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
8946
0
    }
8947
0
#endif
8948
8949
#ifdef HAVE_CURVE25519
8950
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
8951
        cName = "X25519";
8952
    }
8953
#endif
8954
8955
#ifdef HAVE_CURVE448
8956
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
8957
        cName = "X448";
8958
    }
8959
#endif
8960
8961
0
#ifdef HAVE_ECC
8962
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
8963
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
8964
0
                                NULL));
8965
0
    }
8966
0
#endif
8967
8968
0
    return cName;
8969
0
}
8970
#endif
8971
8972
#ifdef OPENSSL_EXTRA
8973
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8974
/* return authentication NID corresponding to cipher suite
8975
 * @param cipher a pointer to WOLFSSL_CIPHER
8976
 * return NID if found, WC_NID_undef if not found
8977
 */
8978
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
8979
{
8980
    static const struct authnid {
8981
        const char* alg_name;
8982
        const int  nid;
8983
    } authnid_tbl[] = {
8984
        {"RSA",     WC_NID_auth_rsa},
8985
        {"PSK",     WC_NID_auth_psk},
8986
        {"SRP",     WC_NID_auth_srp},
8987
        {"ECDSA",   WC_NID_auth_ecdsa},
8988
        {"None",    WC_NID_auth_null},
8989
        {NULL,      WC_NID_undef}
8990
    };
8991
8992
    const char* authStr;
8993
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
8994
8995
    if (GetCipherSegment(cipher, n) == NULL) {
8996
        WOLFSSL_MSG("no suitable cipher name found");
8997
        return WC_NID_undef;
8998
    }
8999
9000
    authStr = GetCipherAuthStr(n);
9001
9002
    if (authStr != NULL) {
9003
        const struct authnid* sa;
9004
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
9005
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
9006
                return sa->nid;
9007
            }
9008
        }
9009
    }
9010
9011
    return WC_NID_undef;
9012
}
9013
/* return cipher NID corresponding to cipher suite
9014
 * @param cipher a pointer to WOLFSSL_CIPHER
9015
 * return NID if found, WC_NID_undef if not found
9016
 */
9017
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
9018
{
9019
    static const struct ciphernid {
9020
        const char* alg_name;
9021
        const int  nid;
9022
    } ciphernid_tbl[] = {
9023
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
9024
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
9025
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
9026
        {"AES(128)",                WC_NID_aes_128_cbc},
9027
        {"AES(256)",                WC_NID_aes_256_cbc},
9028
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
9029
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
9030
        {"RC4",                     WC_NID_rc4},
9031
        {"3DES",                    WC_NID_des_ede3_cbc},
9032
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
9033
        {"None",                    WC_NID_undef},
9034
        {NULL,                      WC_NID_undef}
9035
    };
9036
9037
    const char* encStr;
9038
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9039
9040
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
9041
9042
    if (GetCipherSegment(cipher, n) == NULL) {
9043
        WOLFSSL_MSG("no suitable cipher name found");
9044
        return WC_NID_undef;
9045
    }
9046
9047
    encStr = GetCipherEncStr(n);
9048
9049
    if (encStr != NULL) {
9050
        const struct ciphernid* c;
9051
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
9052
            if (XSTRCMP(c->alg_name, encStr) == 0) {
9053
                return c->nid;
9054
            }
9055
        }
9056
    }
9057
9058
    return WC_NID_undef;
9059
}
9060
/* return digest NID corresponding to cipher suite
9061
 * @param cipher a pointer to WOLFSSL_CIPHER
9062
 * return NID if found, WC_NID_undef if not found
9063
 */
9064
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
9065
{
9066
    static const struct macnid {
9067
        const char* alg_name;
9068
        const int  nid;
9069
    } macnid_tbl[] = {
9070
        {"SHA1",    WC_NID_sha1},
9071
        {"SHA256",  WC_NID_sha256},
9072
        {"SHA384",  WC_NID_sha384},
9073
        {NULL,      WC_NID_undef}
9074
    };
9075
9076
    const char* name;
9077
    const char* macStr;
9078
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9079
    (void)name;
9080
9081
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
9082
9083
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
9084
        WOLFSSL_MSG("no suitable cipher name found");
9085
        return WC_NID_undef;
9086
    }
9087
9088
    /* in MD5 case, NID will be WC_NID_md5 */
9089
    if (XSTRSTR(name, "MD5") != NULL) {
9090
        return WC_NID_md5;
9091
    }
9092
9093
    macStr = GetCipherMacStr(n);
9094
9095
    if (macStr != NULL) {
9096
        const struct macnid* mc;
9097
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
9098
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
9099
                return mc->nid;
9100
            }
9101
        }
9102
    }
9103
9104
    return WC_NID_undef;
9105
}
9106
/* return key exchange NID corresponding to cipher suite
9107
 * @param cipher a pointer to WOLFSSL_CIPHER
9108
 * return NID if found, WC_NID_undef if not found
9109
 */
9110
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
9111
{
9112
    static const struct kxnid {
9113
        const char* name;
9114
        const int  nid;
9115
    } kxnid_table[] = {
9116
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
9117
        {"ECDH",      WC_NID_kx_ecdhe},
9118
        {"DHEPSK",    WC_NID_kx_dhe_psk},
9119
        {"DH",        WC_NID_kx_dhe},
9120
        {"RSAPSK",    WC_NID_kx_rsa_psk},
9121
        {"SRP",       WC_NID_kx_srp},
9122
        {"EDH",       WC_NID_kx_dhe},
9123
        {"PSK",       WC_NID_kx_psk},
9124
        {"RSA",       WC_NID_kx_rsa},
9125
        {NULL,        WC_NID_undef}
9126
    };
9127
9128
    const char* keaStr;
9129
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9130
9131
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
9132
9133
    if (GetCipherSegment(cipher, n) == NULL) {
9134
        WOLFSSL_MSG("no suitable cipher name found");
9135
        return WC_NID_undef;
9136
    }
9137
9138
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
9139
    if (XSTRCMP(n[0], "TLS13") == 0) {
9140
        return WC_NID_kx_any;
9141
    }
9142
9143
    keaStr = GetCipherKeaStr(n);
9144
9145
    if (keaStr != NULL) {
9146
        const struct kxnid* k;
9147
        for(k = kxnid_table; k->name != NULL; k++) {
9148
            if (XSTRCMP(k->name, keaStr) == 0) {
9149
                return k->nid;
9150
            }
9151
        }
9152
    }
9153
9154
    return WC_NID_undef;
9155
}
9156
/* check if cipher suite is AEAD
9157
 * @param cipher a pointer to WOLFSSL_CIPHER
9158
 * return 1 if cipher is AEAD, 0 otherwise
9159
 */
9160
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
9161
{
9162
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9163
9164
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
9165
9166
    if (GetCipherSegment(cipher, n) == NULL) {
9167
        WOLFSSL_MSG("no suitable cipher name found");
9168
        return WC_NID_undef;
9169
    }
9170
9171
    return IsCipherAEAD(n);
9172
}
9173
/* Creates cipher->description based on cipher->offset
9174
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
9175
 * to a stack of ciphers.
9176
 * @param [in] cipher: A cipher from a stack of ciphers.
9177
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
9178
 */
9179
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
9180
{
9181
    int strLen;
9182
    unsigned long offset;
9183
    char* dp;
9184
    const char* name;
9185
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
9186
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9187
    int len = MAX_DESCRIPTION_SZ-1;
9188
    const CipherSuiteInfo* cipher_names;
9189
    ProtocolVersion pv;
9190
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
9191
9192
    if (cipher == NULL)
9193
        return WOLFSSL_FAILURE;
9194
9195
    dp = cipher->description;
9196
    if (dp == NULL)
9197
        return WOLFSSL_FAILURE;
9198
9199
    cipher_names = GetCipherNames();
9200
9201
    offset = cipher->offset;
9202
    if (offset >= (unsigned long)GetCipherNamesSize())
9203
        return WOLFSSL_FAILURE;
9204
    pv.major = cipher_names[offset].major;
9205
    pv.minor = cipher_names[offset].minor;
9206
    protocol = wolfSSL_internal_get_version(&pv);
9207
9208
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
9209
        WOLFSSL_MSG("no suitable cipher name found");
9210
        return WOLFSSL_FAILURE;
9211
    }
9212
9213
    /* keaStr */
9214
    keaStr = GetCipherKeaStr(n);
9215
    /* authStr */
9216
    authStr = GetCipherAuthStr(n);
9217
    /* encStr */
9218
    encStr = GetCipherEncStr(n);
9219
    if ((cipher->bits = SetCipherBits(encStr)) ==
9220
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
9221
    {
9222
       WOLFSSL_MSG("Cipher Bits Not Set.");
9223
    }
9224
    /* macStr */
9225
    macStr = GetCipherMacStr(n);
9226
9227
9228
    /* Build up the string by copying onto the end. */
9229
    XSTRNCPY(dp, name, (size_t)len);
9230
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9231
    len -= strLen; dp += strLen;
9232
9233
    XSTRNCPY(dp, " ", (size_t)len);
9234
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9235
    len -= strLen; dp += strLen;
9236
    XSTRNCPY(dp, protocol, (size_t)len);
9237
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9238
    len -= strLen; dp += strLen;
9239
9240
    XSTRNCPY(dp, " Kx=", (size_t)len);
9241
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9242
    len -= strLen; dp += strLen;
9243
    XSTRNCPY(dp, keaStr, (size_t)len);
9244
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9245
    len -= strLen; dp += strLen;
9246
9247
    XSTRNCPY(dp, " Au=", (size_t)len);
9248
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9249
    len -= strLen; dp += strLen;
9250
    XSTRNCPY(dp, authStr, (size_t)len);
9251
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9252
    len -= strLen; dp += strLen;
9253
9254
    XSTRNCPY(dp, " Enc=", (size_t)len);
9255
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9256
    len -= strLen; dp += strLen;
9257
    XSTRNCPY(dp, encStr, (size_t)len);
9258
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9259
    len -= strLen; dp += strLen;
9260
9261
    XSTRNCPY(dp, " Mac=", (size_t)len);
9262
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9263
    len -= strLen; dp += (size_t)strLen;
9264
    XSTRNCPY(dp, macStr, (size_t)len);
9265
    dp[len-1] = '\0';
9266
9267
    return WOLFSSL_SUCCESS;
9268
}
9269
#endif /* OPENSSL_ALL || WOLFSSL_QT */
9270
9271
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
9272
{
9273
    const char* keaStr;
9274
9275
    switch (kea) {
9276
        case no_kea:
9277
            keaStr = "None";
9278
            break;
9279
#ifndef NO_RSA
9280
        case rsa_kea:
9281
            keaStr = "RSA";
9282
            break;
9283
#endif
9284
#ifndef NO_DH
9285
        case diffie_hellman_kea:
9286
            keaStr = "DHE";
9287
            break;
9288
#endif
9289
        case fortezza_kea:
9290
            keaStr = "FZ";
9291
            break;
9292
#ifndef NO_PSK
9293
        case psk_kea:
9294
            keaStr = "PSK";
9295
            break;
9296
    #ifndef NO_DH
9297
        case dhe_psk_kea:
9298
            keaStr = "DHEPSK";
9299
            break;
9300
    #endif
9301
    #ifdef HAVE_ECC
9302
        case ecdhe_psk_kea:
9303
            keaStr = "ECDHEPSK";
9304
            break;
9305
    #endif
9306
#endif
9307
#ifdef HAVE_ECC
9308
        case ecc_diffie_hellman_kea:
9309
            keaStr = "ECDHE";
9310
            break;
9311
        case ecc_static_diffie_hellman_kea:
9312
            keaStr = "ECDH";
9313
            break;
9314
#endif
9315
        case any_kea:
9316
            keaStr = "any";
9317
            break;
9318
        default:
9319
            keaStr = "unknown";
9320
            break;
9321
    }
9322
9323
    return keaStr;
9324
}
9325
9326
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
9327
{
9328
    const char* authStr;
9329
9330
    switch (sig_algo) {
9331
        case anonymous_sa_algo:
9332
            authStr = "None";
9333
            break;
9334
#ifndef NO_RSA
9335
        case rsa_sa_algo:
9336
            authStr = "RSA";
9337
            break;
9338
    #ifdef WC_RSA_PSS
9339
        case rsa_pss_sa_algo:
9340
            authStr = "RSA-PSS";
9341
            break;
9342
    #endif
9343
#endif
9344
#ifndef NO_DSA
9345
        case dsa_sa_algo:
9346
            authStr = "DSA";
9347
            break;
9348
#endif
9349
#ifdef HAVE_ECC
9350
        case ecc_dsa_sa_algo:
9351
            authStr = "ECDSA";
9352
            break;
9353
#endif
9354
#ifdef WOLFSSL_SM2
9355
        case sm2_sa_algo:
9356
            authStr = "SM2";
9357
            break;
9358
#endif
9359
#ifdef HAVE_ED25519
9360
        case ed25519_sa_algo:
9361
            authStr = "Ed25519";
9362
            break;
9363
#endif
9364
#ifdef HAVE_ED448
9365
        case ed448_sa_algo:
9366
            authStr = "Ed448";
9367
            break;
9368
#endif
9369
        case any_sa_algo:
9370
            authStr = "any";
9371
            break;
9372
        default:
9373
            authStr = "unknown";
9374
            break;
9375
    }
9376
9377
    return authStr;
9378
}
9379
9380
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
9381
{
9382
    const char* encStr;
9383
9384
    (void)key_size;
9385
9386
    switch (cipher) {
9387
        case wolfssl_cipher_null:
9388
            encStr = "None";
9389
            break;
9390
#ifndef NO_RC4
9391
        case wolfssl_rc4:
9392
            encStr = "RC4(128)";
9393
            break;
9394
#endif
9395
#ifndef NO_DES3
9396
        case wolfssl_triple_des:
9397
            encStr = "3DES(168)";
9398
            break;
9399
#endif
9400
#ifndef NO_AES
9401
        case wolfssl_aes:
9402
            if (key_size == AES_128_KEY_SIZE)
9403
                encStr = "AES(128)";
9404
            else if (key_size == AES_256_KEY_SIZE)
9405
                encStr = "AES(256)";
9406
            else
9407
                encStr = "AES(?)";
9408
            break;
9409
    #ifdef HAVE_AESGCM
9410
        case wolfssl_aes_gcm:
9411
            if (key_size == AES_128_KEY_SIZE)
9412
                encStr = "AESGCM(128)";
9413
            else if (key_size == AES_256_KEY_SIZE)
9414
                encStr = "AESGCM(256)";
9415
            else
9416
                encStr = "AESGCM(?)";
9417
            break;
9418
    #endif
9419
    #ifdef HAVE_AESCCM
9420
        case wolfssl_aes_ccm:
9421
            if (key_size == AES_128_KEY_SIZE)
9422
                encStr = "AESCCM(128)";
9423
            else if (key_size == AES_256_KEY_SIZE)
9424
                encStr = "AESCCM(256)";
9425
            else
9426
                encStr = "AESCCM(?)";
9427
            break;
9428
    #endif
9429
#endif
9430
#ifdef HAVE_CHACHA
9431
        case wolfssl_chacha:
9432
            encStr = "CHACHA20/POLY1305(256)";
9433
            break;
9434
#endif
9435
#ifdef HAVE_ARIA
9436
        case wolfssl_aria_gcm:
9437
            if (key_size == ARIA_128_KEY_SIZE)
9438
                encStr = "Aria(128)";
9439
            else if (key_size == ARIA_192_KEY_SIZE)
9440
                encStr = "Aria(192)";
9441
            else if (key_size == ARIA_256_KEY_SIZE)
9442
                encStr = "Aria(256)";
9443
            else
9444
                encStr = "Aria(?)";
9445
            break;
9446
#endif
9447
#ifdef HAVE_CAMELLIA
9448
        case wolfssl_camellia:
9449
            if (key_size == CAMELLIA_128_KEY_SIZE)
9450
                encStr = "Camellia(128)";
9451
            else if (key_size == CAMELLIA_256_KEY_SIZE)
9452
                encStr = "Camellia(256)";
9453
            else
9454
                encStr = "Camellia(?)";
9455
            break;
9456
#endif
9457
        default:
9458
            encStr = "unknown";
9459
            break;
9460
    }
9461
9462
    return encStr;
9463
}
9464
9465
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
9466
{
9467
    const char* macStr;
9468
9469
    switch (mac) {
9470
        case no_mac:
9471
            macStr = "None";
9472
            break;
9473
#ifndef NO_MD5
9474
        case md5_mac:
9475
            macStr = "MD5";
9476
            break;
9477
#endif
9478
#ifndef NO_SHA
9479
        case sha_mac:
9480
            macStr = "SHA1";
9481
            break;
9482
#endif
9483
#ifdef WOLFSSL_SHA224
9484
        case sha224_mac:
9485
            macStr = "SHA224";
9486
            break;
9487
#endif
9488
#ifndef NO_SHA256
9489
        case sha256_mac:
9490
            macStr = "SHA256";
9491
            break;
9492
#endif
9493
#ifdef WOLFSSL_SHA384
9494
        case sha384_mac:
9495
            macStr = "SHA384";
9496
            break;
9497
#endif
9498
#ifdef WOLFSSL_SHA512
9499
        case sha512_mac:
9500
            macStr = "SHA512";
9501
            break;
9502
#endif
9503
        default:
9504
            macStr = "unknown";
9505
            break;
9506
    }
9507
9508
    return macStr;
9509
}
9510
9511
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
9512
                                 int len)
9513
{
9514
    char *ret = in;
9515
    const char *keaStr, *authStr, *encStr, *macStr;
9516
    size_t strLen;
9517
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
9518
9519
    if (cipher == NULL || in == NULL)
9520
        return NULL;
9521
9522
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
9523
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
9524
     * Return the description based on cipher_names[cipher->offset]
9525
     */
9526
    if (cipher->in_stack == TRUE) {
9527
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
9528
        XSTRNCPY(in,cipher->description,(size_t)len);
9529
        return ret;
9530
    }
9531
#endif
9532
9533
    /* Get the cipher description based on the SSL session cipher */
9534
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
9535
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
9536
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
9537
                                      cipher->ssl->specs.key_size);
9538
    if (cipher->ssl->specs.cipher_type == aead)
9539
        macStr = "AEAD";
9540
    else
9541
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
9542
9543
    /* Build up the string by copying onto the end. */
9544
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
9545
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9546
9547
    XSTRNCPY(in, " ", (size_t)len);
9548
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9549
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
9550
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9551
9552
    XSTRNCPY(in, " Kx=", (size_t)len);
9553
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9554
    XSTRNCPY(in, keaStr, (size_t)len);
9555
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9556
9557
    XSTRNCPY(in, " Au=", (size_t)len);
9558
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9559
    XSTRNCPY(in, authStr, (size_t)len);
9560
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9561
9562
    XSTRNCPY(in, " Enc=", (size_t)len);
9563
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9564
    XSTRNCPY(in, encStr, (size_t)len);
9565
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9566
9567
    XSTRNCPY(in, " Mac=", (size_t)len);
9568
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9569
    XSTRNCPY(in, macStr, (size_t)len);
9570
    in[len-1] = '\0';
9571
9572
    return ret;
9573
}
9574
9575
int wolfSSL_OCSP_parse_url(const char* url, char** host, char** port,
9576
        char** path, int* ssl)
9577
{
9578
    const char* u;
9579
    const char* upath; /* path in u */
9580
    const char* uport; /* port in u */
9581
    const char* hostEnd;
9582
9583
    WOLFSSL_ENTER("OCSP_parse_url");
9584
9585
    if (url == NULL || host == NULL || port == NULL || path == NULL ||
9586
            ssl == NULL) {
9587
        return WOLFSSL_FAILURE;
9588
    }
9589
9590
    u = url;
9591
    *host = NULL;
9592
    *port = NULL;
9593
    *path = NULL;
9594
    *ssl = 0;
9595
9596
    if (*(u++) != 'h') goto err;
9597
    if (*(u++) != 't') goto err;
9598
    if (*(u++) != 't') goto err;
9599
    if (*(u++) != 'p') goto err;
9600
    if (*u == 's') {
9601
        *ssl = 1;
9602
        u++;
9603
        *port = CopyString("443", -1, NULL, DYNAMIC_TYPE_OPENSSL);
9604
    }
9605
    else if (*u == ':') {
9606
        *ssl = 0;
9607
        *port = CopyString("80", -1, NULL, DYNAMIC_TYPE_OPENSSL);
9608
    }
9609
    else
9610
        goto err;
9611
    if (*port == NULL)
9612
        goto err;
9613
    if (*(u++) != ':') goto err;
9614
    if (*(u++) != '/') goto err;
9615
    if (*(u++) != '/') goto err;
9616
9617
    /* Look for path */
9618
    upath = XSTRSTR(u, "/");
9619
    *path = CopyString(upath == NULL ? "/" : upath, -1, NULL,
9620
                       DYNAMIC_TYPE_OPENSSL);
9621
9622
    /* Look for port */
9623
    uport = XSTRSTR(u, ":");
9624
    if (uport != NULL) {
9625
        if (*(++uport) == '\0')
9626
            goto err;
9627
        /* port must be before path */
9628
        if (upath != NULL && uport >= upath)
9629
            goto err;
9630
        XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
9631
        if (upath)
9632
            *port = CopyString(uport, (int)(upath - uport), NULL,
9633
                               DYNAMIC_TYPE_OPENSSL);
9634
        else
9635
            *port = CopyString(uport, -1, NULL, DYNAMIC_TYPE_OPENSSL);
9636
        if (*port == NULL)
9637
            goto err;
9638
        hostEnd = uport - 1;
9639
    }
9640
    else
9641
        hostEnd = upath;
9642
9643
    if (hostEnd)
9644
        *host = CopyString(u, (int)(hostEnd - u), NULL, DYNAMIC_TYPE_OPENSSL);
9645
    else
9646
        *host = CopyString(u, -1, NULL, DYNAMIC_TYPE_OPENSSL);
9647
9648
    if (*host == NULL)
9649
        goto err;
9650
9651
    return WOLFSSL_SUCCESS;
9652
err:
9653
    XFREE(*host, NULL, DYNAMIC_TYPE_OPENSSL);
9654
    *host = NULL;
9655
    XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
9656
    *port = NULL;
9657
    XFREE(*path, NULL, DYNAMIC_TYPE_OPENSSL);
9658
    *path = NULL;
9659
    return WOLFSSL_FAILURE;
9660
}
9661
9662
#ifndef NO_WOLFSSL_STUB
9663
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
9664
{
9665
    WOLFSSL_STUB("COMP_zlib");
9666
    return 0;
9667
}
9668
9669
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
9670
{
9671
    WOLFSSL_STUB("COMP_rle");
9672
    return 0;
9673
}
9674
9675
int wolfSSL_COMP_add_compression_method(int method, void* data)
9676
{
9677
    (void)method;
9678
    (void)data;
9679
    WOLFSSL_STUB("COMP_add_compression_method");
9680
    return 0;
9681
}
9682
9683
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
9684
    (void)ssl;
9685
    return NULL;
9686
}
9687
9688
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
9689
    (void)ssl;
9690
    return NULL;
9691
}
9692
9693
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
9694
{
9695
    static const char ret[] = "not supported";
9696
9697
    (void)comp;
9698
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
9699
    return ret;
9700
}
9701
#endif
9702
9703
/*  wolfSSL_set_dynlock_create_callback
9704
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
9705
 *  This function exists for compatibility purposes because wolfSSL satisfies
9706
 *  thread safety without relying on the callback.
9707
 */
9708
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
9709
                                                          const char*, int))
9710
{
9711
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
9712
    (void)f;
9713
}
9714
/*  wolfSSL_set_dynlock_lock_callback
9715
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
9716
 *  This function exists for compatibility purposes because wolfSSL satisfies
9717
 *  thread safety without relying on the callback.
9718
 */
9719
void wolfSSL_set_dynlock_lock_callback(
9720
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
9721
{
9722
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
9723
    (void)f;
9724
}
9725
/*  wolfSSL_set_dynlock_destroy_callback
9726
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
9727
 *  This function exists for compatibility purposes because wolfSSL satisfies
9728
 *  thread safety without relying on the callback.
9729
 */
9730
void wolfSSL_set_dynlock_destroy_callback(
9731
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
9732
{
9733
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
9734
    (void)f;
9735
}
9736
9737
/* Sets the DNS hostname to name.
9738
 * Hostname is cleared if name is NULL or empty. */
9739
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
9740
{
9741
    if (ssl == NULL) {
9742
        return WOLFSSL_FAILURE;
9743
    }
9744
9745
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
9746
}
9747
9748
/******************************************************************************
9749
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
9750
*
9751
* RETURNS:
9752
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
9753
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
9754
*   same as openssl.
9755
*/
9756
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
9757
{
9758
    if (ctx == NULL || vpm == NULL)
9759
        return WOLFSSL_SUCCESS;
9760
9761
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
9762
}
9763
9764
/******************************************************************************
9765
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
9766
*
9767
* RETURNS:
9768
* returns pointer to the SSL verification parameters on success,
9769
* otherwise returns NULL
9770
*/
9771
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
9772
{
9773
    if (ctx == NULL) {
9774
        return NULL;
9775
    }
9776
9777
    return ctx->param;
9778
}
9779
9780
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
9781
{
9782
    if (ssl == NULL) {
9783
        return NULL;
9784
    }
9785
    return ssl->param;
9786
}
9787
9788
#endif /* OPENSSL_EXTRA */
9789
9790
9791
#ifdef OPENSSL_EXTRA
9792
/* Sets a function callback that will send information about the state of all
9793
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
9794
 * in.
9795
 *
9796
 * ctx WOLFSSL_CTX structure to set callback function in
9797
 * f   callback function to use
9798
 */
9799
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
9800
       void (*f)(const WOLFSSL* ssl, int type, int val))
9801
{
9802
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
9803
    if (ctx == NULL) {
9804
        WOLFSSL_MSG("Bad function argument");
9805
    }
9806
    else {
9807
        ctx->CBIS = f;
9808
    }
9809
}
9810
9811
void wolfSSL_set_info_callback(WOLFSSL* ssl,
9812
       void (*f)(const WOLFSSL* ssl, int type, int val))
9813
{
9814
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
9815
    if (ssl == NULL) {
9816
        WOLFSSL_MSG("Bad function argument");
9817
    }
9818
    else {
9819
        ssl->CBIS = f;
9820
    }
9821
}
9822
9823
9824
unsigned long wolfSSL_ERR_peek_error(void)
9825
{
9826
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error");
9827
9828
    return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL);
9829
}
9830
9831
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H
9832
#include <wolfssl/debug-untrace-error-codes.h>
9833
#endif
9834
9835
int wolfSSL_ERR_GET_LIB(unsigned long err)
9836
{
9837
    unsigned long value;
9838
9839
    value = (err & 0xFFFFFFL);
9840
    switch (value) {
9841
    case -PARSE_ERROR:
9842
        return WOLFSSL_ERR_LIB_SSL;
9843
    case -ASN_NO_PEM_HEADER:
9844
    case -WOLFSSL_PEM_R_NO_START_LINE_E:
9845
    case -WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E:
9846
    case -WOLFSSL_PEM_R_BAD_PASSWORD_READ_E:
9847
    case -WOLFSSL_PEM_R_BAD_DECRYPT_E:
9848
        return WOLFSSL_ERR_LIB_PEM;
9849
    case -WOLFSSL_EVP_R_BAD_DECRYPT_E:
9850
    case -WOLFSSL_EVP_R_BN_DECODE_ERROR:
9851
    case -WOLFSSL_EVP_R_DECODE_ERROR:
9852
    case -WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR:
9853
        return WOLFSSL_ERR_LIB_EVP;
9854
    case -WOLFSSL_ASN1_R_HEADER_TOO_LONG_E:
9855
        return WOLFSSL_ERR_LIB_ASN1;
9856
    default:
9857
        return 0;
9858
    }
9859
}
9860
9861
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES
9862
#include <wolfssl/debug-trace-error-codes.h>
9863
#endif
9864
9865
/* This function is to find global error values that are the same through out
9866
 * all library version. With wolfSSL having only one set of error codes the
9867
 * return value is pretty straight forward. The only thing needed is all wolfSSL
9868
 * error values are typically negative.
9869
 *
9870
 * Returns the error reason
9871
 */
9872
int wolfSSL_ERR_GET_REASON(unsigned long err)
9873
{
9874
    int ret = (int)err;
9875
9876
    WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON");
9877
9878
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
9879
    /* Nginx looks for this error to know to stop parsing certificates.
9880
     * Same for HAProxy. */
9881
    if ((err == (unsigned long)((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE)) ||
9882
        ((err & 0xFFFFFFL) == (unsigned long)(-WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))) ||
9883
        ((err & 0xFFFL) == (unsigned long)PEM_R_NO_START_LINE))
9884
        return PEM_R_NO_START_LINE;
9885
    if (err == (unsigned long)((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST))
9886
        return SSL_R_HTTP_REQUEST;
9887
#endif
9888
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
9889
    if (err == (unsigned long)((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG))
9890
        return ASN1_R_HEADER_TOO_LONG;
9891
#endif
9892
9893
    /* check if error value is in range of wolfCrypt or wolfSSL errors */
9894
    ret = 0 - ret; /* setting as negative value */
9895
9896
    if ((ret <= WC_SPAN1_FIRST_E && ret >= WC_SPAN1_LAST_E) ||
9897
        (ret <= WC_SPAN2_FIRST_E && ret >= WC_SPAN2_LAST_E) ||
9898
        (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E))
9899
    {
9900
        return ret;
9901
    }
9902
    else {
9903
        WOLFSSL_MSG("Not in range of typical error values");
9904
        ret = (int)err;
9905
    }
9906
9907
    return ret;
9908
}
9909
9910
#ifndef NO_TLS
9911
/* returns a string that describes the alert
9912
 *
9913
 * alertID the alert value to look up
9914
 */
9915
const char* wolfSSL_alert_type_string_long(int alertID)
9916
{
9917
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
9918
9919
    return AlertTypeToString(alertID);
9920
}
9921
9922
const char* wolfSSL_alert_type_string(int alertID)
9923
{
9924
    WOLFSSL_ENTER("wolfSSL_alert_type_string");
9925
9926
    switch (alertID) {
9927
        case alert_warning:
9928
            return "W";
9929
        case alert_fatal:
9930
            return "F";
9931
        default:
9932
            return "U";
9933
    }
9934
}
9935
9936
const char* wolfSSL_alert_desc_string_long(int alertID)
9937
{
9938
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
9939
9940
    return AlertTypeToString(alertID);
9941
}
9942
9943
const char* wolfSSL_alert_desc_string(int alertID)
9944
{
9945
    WOLFSSL_ENTER("wolfSSL_alert_desc_string");
9946
9947
    switch (alertID) {
9948
        case close_notify:
9949
            return "CN";
9950
        case unexpected_message:
9951
            return "UM";
9952
        case bad_record_mac:
9953
            return "BM";
9954
        case record_overflow:
9955
            return "RO";
9956
        case decompression_failure:
9957
            return "DF";
9958
        case handshake_failure:
9959
            return "HF";
9960
        case no_certificate:
9961
            return "NC";
9962
        case bad_certificate:
9963
            return "BC";
9964
        case unsupported_certificate:
9965
            return "UC";
9966
        case certificate_revoked:
9967
            return "CR";
9968
        case certificate_expired:
9969
            return "CE";
9970
        case certificate_unknown:
9971
            return "CU";
9972
        case illegal_parameter:
9973
            return "IP";
9974
        case unknown_ca:
9975
            return "CA";
9976
        case access_denied:
9977
            return "AD";
9978
        case decode_error:
9979
            return "DE";
9980
        case decrypt_error:
9981
            return "DC";
9982
        case wolfssl_alert_protocol_version:
9983
            return "PV";
9984
        case insufficient_security:
9985
            return "IS";
9986
        case internal_error:
9987
            return "IE";
9988
        case inappropriate_fallback:
9989
            return "IF";
9990
        case user_canceled:
9991
            return "US";
9992
        case no_renegotiation:
9993
            return "NR";
9994
        case missing_extension:
9995
            return "ME";
9996
        case unsupported_extension:
9997
            return "UE";
9998
        case unrecognized_name:
9999
            return "UN";
10000
        case bad_certificate_status_response:
10001
            return "BR";
10002
        case unknown_psk_identity:
10003
            return "UP";
10004
        case certificate_required:
10005
            return "CQ";
10006
        case no_application_protocol:
10007
            return "AP";
10008
        default:
10009
            return "UK";
10010
    }
10011
}
10012
#endif /* !NO_TLS */
10013
10014
#define STATE_STRINGS_PROTO(s) \
10015
    {                          \
10016
        {"SSLv3 " s,           \
10017
         "SSLv3 " s,           \
10018
         "SSLv3 " s},          \
10019
        {"TLSv1 " s,           \
10020
         "TLSv1 " s,           \
10021
         "TLSv1 " s},          \
10022
        {"TLSv1_1 " s,         \
10023
         "TLSv1_1 " s,         \
10024
         "TLSv1_1 " s},        \
10025
        {"TLSv1_2 " s,         \
10026
         "TLSv1_2 " s,         \
10027
         "TLSv1_2 " s},        \
10028
        {"TLSv1_3 " s,         \
10029
         "TLSv1_3 " s,         \
10030
         "TLSv1_3 " s},        \
10031
        {"DTLSv1 " s,          \
10032
         "DTLSv1 " s,          \
10033
         "DTLSv1 " s},         \
10034
        {"DTLSv1_2 " s,        \
10035
         "DTLSv1_2 " s,        \
10036
         "DTLSv1_2 " s},       \
10037
        {"DTLSv1_3 " s,        \
10038
         "DTLSv1_3 " s,        \
10039
         "DTLSv1_3 " s},       \
10040
    }
10041
10042
#define STATE_STRINGS_PROTO_RW(s) \
10043
    {                             \
10044
        {"SSLv3 read " s,         \
10045
         "SSLv3 write " s,        \
10046
         "SSLv3 " s},             \
10047
        {"TLSv1 read " s,         \
10048
         "TLSv1 write " s,        \
10049
         "TLSv1 " s},             \
10050
        {"TLSv1_1 read " s,       \
10051
         "TLSv1_1 write " s,      \
10052
         "TLSv1_1 " s},           \
10053
        {"TLSv1_2 read " s,       \
10054
         "TLSv1_2 write " s,      \
10055
         "TLSv1_2 " s},           \
10056
        {"TLSv1_3 read " s,       \
10057
         "TLSv1_3 write " s,      \
10058
         "TLSv1_3 " s},           \
10059
        {"DTLSv1 read " s,        \
10060
         "DTLSv1 write " s,       \
10061
         "DTLSv1 " s},            \
10062
        {"DTLSv1_2 read " s,      \
10063
         "DTLSv1_2 write " s,     \
10064
         "DTLSv1_2 " s},          \
10065
        {"DTLSv1_3 read " s,      \
10066
         "DTLSv1_3 write " s,     \
10067
         "DTLSv1_3 " s},          \
10068
    }
10069
10070
/* Gets the current state of the WOLFSSL structure
10071
 *
10072
 * ssl WOLFSSL structure to get state of
10073
 *
10074
 * Returns a human readable string of the WOLFSSL structure state
10075
 */
10076
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
10077
{
10078
10079
    static const char* OUTPUT_STR[24][8][3] = {
10080
        STATE_STRINGS_PROTO("Initialization"),
10081
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
10082
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
10083
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
10084
        STATE_STRINGS_PROTO_RW("Server Hello"),
10085
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
10086
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
10087
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
10088
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
10089
        STATE_STRINGS_PROTO_RW("Server Cert"),
10090
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
10091
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
10092
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
10093
        STATE_STRINGS_PROTO_RW("Server Finished"),
10094
        STATE_STRINGS_PROTO_RW("server Key Update"),
10095
        STATE_STRINGS_PROTO_RW("Client Hello"),
10096
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
10097
        STATE_STRINGS_PROTO_RW("Client Cert"),
10098
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
10099
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
10100
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
10101
        STATE_STRINGS_PROTO_RW("Client Finished"),
10102
        STATE_STRINGS_PROTO_RW("Client Key Update"),
10103
        STATE_STRINGS_PROTO("Handshake Done"),
10104
    };
10105
    enum ProtocolVer {
10106
        SSL_V3 = 0,
10107
        TLS_V1,
10108
        TLS_V1_1,
10109
        TLS_V1_2,
10110
        TLS_V1_3,
10111
        DTLS_V1,
10112
        DTLS_V1_2,
10113
        DTLS_V1_3,
10114
        UNKNOWN = 100
10115
    };
10116
10117
    enum IOMode {
10118
        SS_READ = 0,
10119
        SS_WRITE,
10120
        SS_NEITHER
10121
    };
10122
10123
    enum SslState {
10124
        ss_null_state = 0,
10125
        ss_server_hellorequest,
10126
        ss_server_helloverify,
10127
        ss_server_helloretryrequest,
10128
        ss_server_hello,
10129
        ss_server_certificatestatus,
10130
        ss_server_encryptedextensions,
10131
        ss_server_sessionticket,
10132
        ss_server_certrequest,
10133
        ss_server_cert,
10134
        ss_server_keyexchange,
10135
        ss_server_hellodone,
10136
        ss_server_changecipherspec,
10137
        ss_server_finished,
10138
        ss_server_keyupdate,
10139
        ss_client_hello,
10140
        ss_client_keyexchange,
10141
        ss_client_cert,
10142
        ss_client_changecipherspec,
10143
        ss_client_certverify,
10144
        ss_client_endofearlydata,
10145
        ss_client_finished,
10146
        ss_client_keyupdate,
10147
        ss_handshake_done
10148
    };
10149
10150
    int protocol = 0;
10151
    int cbmode = 0;
10152
    int state = 0;
10153
10154
    WOLFSSL_ENTER("wolfSSL_state_string_long");
10155
    if (ssl == NULL) {
10156
        WOLFSSL_MSG("Null argument passed in");
10157
        return NULL;
10158
    }
10159
10160
    /* Get state of callback */
10161
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
10162
        cbmode =  SS_WRITE;
10163
    }
10164
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
10165
        cbmode =  SS_READ;
10166
    }
10167
    else {
10168
        cbmode =  SS_NEITHER;
10169
    }
10170
10171
    /* Get protocol version */
10172
    switch (ssl->version.major) {
10173
        case SSLv3_MAJOR:
10174
            switch (ssl->version.minor) {
10175
                case SSLv3_MINOR:
10176
                    protocol = SSL_V3;
10177
                    break;
10178
                case TLSv1_MINOR:
10179
                    protocol = TLS_V1;
10180
                    break;
10181
                case TLSv1_1_MINOR:
10182
                    protocol = TLS_V1_1;
10183
                    break;
10184
                case TLSv1_2_MINOR:
10185
                    protocol = TLS_V1_2;
10186
                    break;
10187
                case TLSv1_3_MINOR:
10188
                    protocol = TLS_V1_3;
10189
                    break;
10190
                default:
10191
                    protocol = UNKNOWN;
10192
            }
10193
            break;
10194
        case DTLS_MAJOR:
10195
            switch (ssl->version.minor) {
10196
                case DTLS_MINOR:
10197
                    protocol = DTLS_V1;
10198
                    break;
10199
                case DTLSv1_2_MINOR:
10200
                    protocol = DTLS_V1_2;
10201
                    break;
10202
                case DTLSv1_3_MINOR:
10203
                    protocol = DTLS_V1_3;
10204
                    break;
10205
                default:
10206
                    protocol = UNKNOWN;
10207
            }
10208
            break;
10209
    default:
10210
        protocol = UNKNOWN;
10211
    }
10212
10213
    /* accept process */
10214
    if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
10215
        state = ssl->cbtype;
10216
        switch (state) {
10217
            case hello_request:
10218
                state = ss_server_hellorequest;
10219
                break;
10220
            case client_hello:
10221
                state = ss_client_hello;
10222
                break;
10223
            case server_hello:
10224
                state = ss_server_hello;
10225
                break;
10226
            case hello_verify_request:
10227
                state = ss_server_helloverify;
10228
                break;
10229
            case session_ticket:
10230
                state = ss_server_sessionticket;
10231
                break;
10232
            case end_of_early_data:
10233
                state = ss_client_endofearlydata;
10234
                break;
10235
            case hello_retry_request:
10236
                state = ss_server_helloretryrequest;
10237
                break;
10238
            case encrypted_extensions:
10239
                state = ss_server_encryptedextensions;
10240
                break;
10241
            case certificate:
10242
                if (ssl->options.side == WOLFSSL_SERVER_END)
10243
                    state = ss_client_cert;
10244
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10245
                    state = ss_server_cert;
10246
                else {
10247
                    WOLFSSL_MSG("Unknown State");
10248
                    state = ss_null_state;
10249
                }
10250
                break;
10251
            case server_key_exchange:
10252
                state = ss_server_keyexchange;
10253
                break;
10254
            case certificate_request:
10255
                state = ss_server_certrequest;
10256
                break;
10257
            case server_hello_done:
10258
                state = ss_server_hellodone;
10259
                break;
10260
            case certificate_verify:
10261
                state = ss_client_certverify;
10262
                break;
10263
            case client_key_exchange:
10264
                state = ss_client_keyexchange;
10265
                break;
10266
            case finished:
10267
                if (ssl->options.side == WOLFSSL_SERVER_END)
10268
                    state = ss_client_finished;
10269
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10270
                    state = ss_server_finished;
10271
                else {
10272
                    WOLFSSL_MSG("Unknown State");
10273
                    state = ss_null_state;
10274
                }
10275
                break;
10276
            case certificate_status:
10277
                state = ss_server_certificatestatus;
10278
                break;
10279
            case key_update:
10280
                if (ssl->options.side == WOLFSSL_SERVER_END)
10281
                    state = ss_client_keyupdate;
10282
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10283
                    state = ss_server_keyupdate;
10284
                else {
10285
                    WOLFSSL_MSG("Unknown State");
10286
                    state = ss_null_state;
10287
                }
10288
                break;
10289
            case change_cipher_hs:
10290
                if (ssl->options.side == WOLFSSL_SERVER_END)
10291
                    state = ss_client_changecipherspec;
10292
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10293
                    state = ss_server_changecipherspec;
10294
                else {
10295
                    WOLFSSL_MSG("Unknown State");
10296
                    state = ss_null_state;
10297
                }
10298
                break;
10299
            default:
10300
                WOLFSSL_MSG("Unknown State");
10301
                state = ss_null_state;
10302
        }
10303
    }
10304
    else {
10305
        /* Send process */
10306
        if (ssl->options.side == WOLFSSL_SERVER_END)
10307
            state = ssl->options.serverState;
10308
        else
10309
            state = ssl->options.clientState;
10310
10311
        switch (state) {
10312
            case SERVER_HELLOVERIFYREQUEST_COMPLETE:
10313
                state = ss_server_helloverify;
10314
                break;
10315
            case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
10316
                state = ss_server_helloretryrequest;
10317
                break;
10318
            case SERVER_HELLO_COMPLETE:
10319
                state = ss_server_hello;
10320
                break;
10321
            case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
10322
                state = ss_server_encryptedextensions;
10323
                break;
10324
            case SERVER_CERT_COMPLETE:
10325
                state = ss_server_cert;
10326
                break;
10327
            case SERVER_KEYEXCHANGE_COMPLETE:
10328
                state = ss_server_keyexchange;
10329
                break;
10330
            case SERVER_HELLODONE_COMPLETE:
10331
                state = ss_server_hellodone;
10332
                break;
10333
            case SERVER_CHANGECIPHERSPEC_COMPLETE:
10334
                state = ss_server_changecipherspec;
10335
                break;
10336
            case SERVER_FINISHED_COMPLETE:
10337
                state = ss_server_finished;
10338
                break;
10339
            case CLIENT_HELLO_RETRY:
10340
            case CLIENT_HELLO_COMPLETE:
10341
                state = ss_client_hello;
10342
                break;
10343
            case CLIENT_KEYEXCHANGE_COMPLETE:
10344
                state = ss_client_keyexchange;
10345
                break;
10346
            case CLIENT_CHANGECIPHERSPEC_COMPLETE:
10347
                state = ss_client_changecipherspec;
10348
                break;
10349
            case CLIENT_FINISHED_COMPLETE:
10350
                state = ss_client_finished;
10351
                break;
10352
            case HANDSHAKE_DONE:
10353
                state = ss_handshake_done;
10354
                break;
10355
            default:
10356
                WOLFSSL_MSG("Unknown State");
10357
                state = ss_null_state;
10358
        }
10359
    }
10360
10361
    if (protocol == UNKNOWN) {
10362
        WOLFSSL_MSG("Unknown protocol");
10363
        return "";
10364
    }
10365
    else {
10366
        return OUTPUT_STR[state][protocol][cbmode];
10367
    }
10368
}
10369
10370
#endif /* OPENSSL_EXTRA */
10371
10372
static long wolf_set_options(long old_op, long op)
10373
0
{
10374
    /* if SSL_OP_ALL then turn all bug workarounds on */
10375
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
10376
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
10377
0
    }
10378
10379
    /* by default cookie exchange is on with DTLS */
10380
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
10381
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
10382
0
    }
10383
10384
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
10385
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
10386
0
    }
10387
10388
#ifdef SSL_OP_NO_TLSv1_3
10389
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
10390
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
10391
    }
10392
#endif
10393
10394
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
10395
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
10396
0
    }
10397
10398
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
10399
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
10400
0
    }
10401
10402
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
10403
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
10404
0
    }
10405
10406
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
10407
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
10408
0
    }
10409
10410
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
10411
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
10412
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
10413
0
    }
10414
10415
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
10416
    #ifdef HAVE_LIBZ
10417
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
10418
    #else
10419
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
10420
0
    #endif
10421
0
    }
10422
10423
0
    return old_op | op;
10424
0
}
10425
10426
static int FindHashSig(const Suites* suites, byte first, byte second)
10427
0
{
10428
0
    word16 i;
10429
10430
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
10431
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
10432
0
        return SUITES_ERROR;
10433
0
    }
10434
10435
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
10436
0
        if (suites->hashSigAlgo[i]   == first &&
10437
0
            suites->hashSigAlgo[i+1] == second )
10438
0
            return i;
10439
0
    }
10440
10441
0
    return MATCH_SUITE_ERROR;
10442
0
}
10443
10444
long wolfSSL_set_options(WOLFSSL* ssl, long op)
10445
0
{
10446
0
    word16 haveRSA = 1;
10447
0
    word16 havePSK = 0;
10448
0
    int    keySz   = 0;
10449
10450
0
    WOLFSSL_ENTER("wolfSSL_set_options");
10451
10452
0
    if (ssl == NULL) {
10453
0
        return 0;
10454
0
    }
10455
10456
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
10457
10458
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
10459
0
        WOLFSSL_MSG("Disabling TLS 1.3");
10460
0
        if (ssl->version.minor == TLSv1_3_MINOR)
10461
0
            ssl->version.minor = TLSv1_2_MINOR;
10462
0
    }
10463
10464
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
10465
0
        WOLFSSL_MSG("Disabling TLS 1.2");
10466
0
        if (ssl->version.minor == TLSv1_2_MINOR)
10467
0
            ssl->version.minor = TLSv1_1_MINOR;
10468
0
    }
10469
10470
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
10471
0
        WOLFSSL_MSG("Disabling TLS 1.1");
10472
0
        if (ssl->version.minor == TLSv1_1_MINOR)
10473
0
            ssl->version.minor = TLSv1_MINOR;
10474
0
    }
10475
10476
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
10477
0
        WOLFSSL_MSG("Disabling TLS 1.0");
10478
0
        if (ssl->version.minor == TLSv1_MINOR)
10479
0
            ssl->version.minor = SSLv3_MINOR;
10480
0
    }
10481
10482
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
10483
0
        == WOLFSSL_OP_NO_COMPRESSION) {
10484
    #ifdef HAVE_LIBZ
10485
        ssl->options.usingCompression = 0;
10486
    #endif
10487
0
    }
10488
10489
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
10490
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
10491
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
10492
      ssl->options.noTicketTls12 = 1;
10493
    }
10494
#endif
10495
10496
10497
    /* in the case of a version change the cipher suites should be reset */
10498
#ifndef NO_PSK
10499
    havePSK = ssl->options.havePSK;
10500
#endif
10501
#ifdef NO_RSA
10502
    haveRSA = 0;
10503
#endif
10504
0
#ifndef NO_CERTS
10505
0
    keySz = ssl->buffers.keySz;
10506
0
#endif
10507
10508
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
10509
0
        if (AllocateSuites(ssl) != 0)
10510
0
            return 0;
10511
0
        if (!ssl->suites->setSuites) {
10512
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
10513
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
10514
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
10515
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
10516
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
10517
0
                       ssl->options.useAnon,
10518
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
10519
0
            else
10520
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
10521
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
10522
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
10523
0
                       ssl->options.useAnon,
10524
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
10525
0
        }
10526
0
        else {
10527
            /* Only preserve overlapping suites */
10528
0
            Suites tmpSuites;
10529
0
            word16 in, out;
10530
0
            word16 haveECDSAsig, haveStaticECC;
10531
#ifdef NO_RSA
10532
            haveECDSAsig = 1;
10533
            haveStaticECC = 1;
10534
#else
10535
0
            haveECDSAsig = 0;
10536
0
            haveStaticECC = ssl->options.haveStaticECC;
10537
0
#endif
10538
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
10539
            /* Get all possible ciphers and sigalgs for the version. Following
10540
             * options limit the allowed ciphers so let's try to get as many as
10541
             * possible.
10542
             * - haveStaticECC turns off haveRSA
10543
             * - haveECDSAsig turns off haveRSAsig */
10544
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
10545
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
10546
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
10547
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
10548
0
                        ssl->suites->suites[in+1]) >= 0) {
10549
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
10550
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
10551
0
                    out += SUITE_LEN;
10552
0
                }
10553
0
            }
10554
0
            ssl->suites->suiteSz = out;
10555
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
10556
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
10557
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
10558
0
                    ssl->suites->hashSigAlgo[out] =
10559
0
                            ssl->suites->hashSigAlgo[in];
10560
0
                    ssl->suites->hashSigAlgo[out+1] =
10561
0
                            ssl->suites->hashSigAlgo[in+1];
10562
0
                    out += 2;
10563
0
                }
10564
0
            }
10565
0
            ssl->suites->hashSigAlgoSz = out;
10566
0
        }
10567
0
    }
10568
10569
0
    return (long)ssl->options.mask;
10570
0
}
10571
10572
10573
long wolfSSL_get_options(const WOLFSSL* ssl)
10574
0
{
10575
0
    WOLFSSL_ENTER("wolfSSL_get_options");
10576
0
    if(ssl == NULL)
10577
0
        return WOLFSSL_FAILURE;
10578
0
    return (long)ssl->options.mask;
10579
0
}
10580
10581
#if defined(HAVE_SECURE_RENEGOTIATION) \
10582
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
10583
/* clears the counter for number of renegotiations done
10584
 * returns the current count before it is cleared */
10585
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
10586
0
{
10587
0
    long total;
10588
10589
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
10590
0
    if (s == NULL)
10591
0
        return 0;
10592
10593
0
    total = s->secure_rene_count;
10594
0
    s->secure_rene_count = 0;
10595
0
    return total;
10596
0
}
10597
10598
10599
/* return the number of renegotiations since wolfSSL_new */
10600
long wolfSSL_total_renegotiations(WOLFSSL *s)
10601
0
{
10602
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
10603
0
    return wolfSSL_num_renegotiations(s);
10604
0
}
10605
10606
10607
/* return the number of renegotiations since wolfSSL_new */
10608
long wolfSSL_num_renegotiations(WOLFSSL* s)
10609
0
{
10610
0
    if (s == NULL) {
10611
0
        return 0;
10612
0
    }
10613
10614
0
    return s->secure_rene_count;
10615
0
}
10616
10617
10618
/* Is there a renegotiation currently in progress? */
10619
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
10620
0
{
10621
0
    return s && s->options.handShakeDone &&
10622
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
10623
0
}
10624
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
10625
10626
#ifdef OPENSSL_EXTRA
10627
10628
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
10629
{
10630
    WOLFSSL_ENTER("wolfSSL_clear_options");
10631
    if(ssl == NULL)
10632
        return WOLFSSL_FAILURE;
10633
    ssl->options.mask &= (unsigned long)~opt;
10634
    return (long)ssl->options.mask;
10635
}
10636
10637
10638
#ifndef NO_WOLFSSL_STUB
10639
/*** TBD ***/
10640
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
10641
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
10642
{
10643
    (void)ctx;
10644
    (void)dh;
10645
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
10646
}
10647
#endif
10648
10649
#ifndef NO_WOLFSSL_STUB
10650
/*** TBD ***/
10651
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
10652
{
10653
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
10654
    return NULL;
10655
}
10656
#endif
10657
10658
10659
#if !defined(NETOS)
10660
void wolfSSL_ERR_load_SSL_strings(void)
10661
{
10662
10663
}
10664
#endif
10665
10666
10667
#endif /* OPENSSL_EXTRA */
10668
10669
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
10670
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
10671
{
10672
    byte len = 0;
10673
    byte const * src;
10674
10675
    WOLFSSL_ENTER("wolfSSL_get_finished");
10676
10677
    if (!ssl || !buf) {
10678
        WOLFSSL_MSG("Bad parameter");
10679
        return WOLFSSL_FAILURE;
10680
    }
10681
10682
    if (ssl->options.side == WOLFSSL_SERVER_END) {
10683
        src = ssl->serverFinished;
10684
        len = ssl->serverFinished_len;
10685
    }
10686
    else {
10687
        src = ssl->clientFinished;
10688
        len = ssl->clientFinished_len;
10689
    }
10690
10691
    if (count < len) {
10692
        WOLFSSL_MSG("Buffer too small");
10693
        return WOLFSSL_FAILURE;
10694
    }
10695
10696
    XMEMCPY(buf, src, len);
10697
10698
    return len;
10699
}
10700
10701
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
10702
{
10703
    byte len = 0;
10704
    byte const * src;
10705
10706
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
10707
10708
    if (!ssl || !buf) {
10709
        WOLFSSL_MSG("Bad parameter");
10710
        return WOLFSSL_FAILURE;
10711
    }
10712
10713
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
10714
        src = ssl->serverFinished;
10715
        len = ssl->serverFinished_len;
10716
    }
10717
    else {
10718
        src = ssl->clientFinished;
10719
        len = ssl->clientFinished_len;
10720
    }
10721
10722
    if (count < len) {
10723
        WOLFSSL_MSG("Buffer too small");
10724
        return WOLFSSL_FAILURE;
10725
    }
10726
10727
    XMEMCPY(buf, src, len);
10728
10729
    return len;
10730
}
10731
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
10732
10733
10734
#ifdef OPENSSL_EXTRA
10735
10736
#ifndef NO_WOLFSSL_STUB
10737
/* shows the number of accepts attempted by CTX in it's lifetime */
10738
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
10739
{
10740
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
10741
    (void)ctx;
10742
    return 0;
10743
}
10744
#endif
10745
10746
#ifndef NO_WOLFSSL_STUB
10747
/* shows the number of connects attempted CTX in it's lifetime */
10748
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
10749
{
10750
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
10751
    (void)ctx;
10752
    return 0;
10753
}
10754
#endif
10755
10756
10757
#ifndef NO_WOLFSSL_STUB
10758
/* shows the number of accepts completed by CTX in it's lifetime */
10759
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
10760
{
10761
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
10762
    (void)ctx;
10763
    return 0;
10764
}
10765
#endif
10766
10767
10768
#ifndef NO_WOLFSSL_STUB
10769
/* shows the number of connects completed by CTX in it's lifetime */
10770
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
10771
{
10772
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
10773
    (void)ctx;
10774
    return 0;
10775
}
10776
#endif
10777
10778
10779
#ifndef NO_WOLFSSL_STUB
10780
/* shows the number of renegotiation accepts attempted by CTX */
10781
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
10782
{
10783
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
10784
    (void)ctx;
10785
    return 0;
10786
}
10787
#endif
10788
10789
10790
#ifndef NO_WOLFSSL_STUB
10791
/* shows the number of renegotiation accepts attempted by CTX */
10792
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
10793
{
10794
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
10795
    (void)ctx;
10796
    return 0;
10797
}
10798
#endif
10799
10800
10801
#ifndef NO_WOLFSSL_STUB
10802
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
10803
{
10804
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
10805
    (void)ctx;
10806
    return 0;
10807
}
10808
#endif
10809
10810
10811
#ifndef NO_WOLFSSL_STUB
10812
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
10813
{
10814
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
10815
    (void)ctx;
10816
    return 0;
10817
}
10818
#endif
10819
10820
10821
#ifndef NO_WOLFSSL_STUB
10822
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
10823
{
10824
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
10825
    (void)ctx;
10826
    return 0;
10827
}
10828
#endif
10829
10830
10831
#ifndef NO_WOLFSSL_STUB
10832
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
10833
{
10834
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
10835
    (void)ctx;
10836
    return 0;
10837
}
10838
#endif
10839
10840
10841
#ifndef NO_WOLFSSL_STUB
10842
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
10843
{
10844
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
10845
    (void)ctx;
10846
    return 0;
10847
}
10848
#endif
10849
10850
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
10851
{
10852
    if (ssl == NULL) {
10853
        return WOLFSSL_FAILURE;
10854
    }
10855
10856
    return ssl->readAhead;
10857
}
10858
10859
10860
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
10861
{
10862
    if (ssl == NULL) {
10863
        return WOLFSSL_FAILURE;
10864
    }
10865
10866
    ssl->readAhead = (byte)v;
10867
10868
    return WOLFSSL_SUCCESS;
10869
}
10870
10871
10872
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
10873
{
10874
    if (ctx == NULL) {
10875
        return WOLFSSL_FAILURE;
10876
    }
10877
10878
    return ctx->readAhead;
10879
}
10880
10881
10882
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
10883
{
10884
    if (ctx == NULL) {
10885
        return WOLFSSL_FAILURE;
10886
    }
10887
10888
    ctx->readAhead = (byte)v;
10889
10890
    return WOLFSSL_SUCCESS;
10891
}
10892
10893
10894
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
10895
        void* arg)
10896
{
10897
    if (ctx == NULL) {
10898
        return WOLFSSL_FAILURE;
10899
    }
10900
10901
    ctx->userPRFArg = arg;
10902
    return WOLFSSL_SUCCESS;
10903
}
10904
10905
#endif /* OPENSSL_EXTRA */
10906
10907
10908
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
10909
const WOLFSSL_ObjectInfo wolfssl_object_info[] = {
10910
#ifndef NO_CERTS
10911
    /* oidCertExtType */
10912
    { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType,
10913
      "basicConstraints", "X509v3 Basic Constraints"},
10914
    { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName",
10915
      "X509v3 Subject Alternative Name"},
10916
    { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType,
10917
      "crlDistributionPoints", "X509v3 CRL Distribution Points"},
10918
    { WC_NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess",
10919
      "Authority Information Access"},
10920
    { WC_NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType,
10921
      "authorityKeyIdentifier", "X509v3 Authority Key Identifier"},
10922
    { WC_NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType,
10923
      "subjectKeyIdentifier", "X509v3 Subject Key Identifier"},
10924
    { WC_NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage",
10925
      "X509v3 Key Usage"},
10926
    { WC_NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType,
10927
      "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"},
10928
    { WC_NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType,
10929
      "extendedKeyUsage", "X509v3 Extended Key Usage"},
10930
    { WC_NID_name_constraints, NAME_CONS_OID, oidCertExtType,
10931
      "nameConstraints", "X509v3 Name Constraints"},
10932
    { WC_NID_certificate_policies, CERT_POLICY_OID, oidCertExtType,
10933
      "certificatePolicies", "X509v3 Certificate Policies"},
10934
10935
    /* oidCertAuthInfoType */
10936
    { WC_NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP",
10937
      "OCSP"},
10938
    { WC_NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType,
10939
      "caIssuers", "CA Issuers"},
10940
10941
    /* oidCertPolicyType */
10942
    { WC_NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy",
10943
      "X509v3 Any Policy"},
10944
10945
    /* oidCertAltNameType */
10946
    { WC_NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""},
10947
10948
    /* oidCertKeyUseType */
10949
    { WC_NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType,
10950
      "anyExtendedKeyUsage", "Any Extended Key Usage"},
10951
    { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType,
10952
      "serverAuth", "TLS Web Server Authentication"},
10953
    { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType,
10954
      "clientAuth", "TLS Web Client Authentication"},
10955
    { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType,
10956
      "OCSPSigning", "OCSP Signing"},
10957
10958
    /* oidCertNameType */
10959
    { WC_NID_commonName, WC_NAME_COMMON_NAME_OID, oidCertNameType,
10960
      "CN", "commonName"},
10961
#if !defined(WOLFSSL_CERT_REQ)
10962
    { WC_NID_surname, WC_NAME_SURNAME_OID, oidCertNameType, "SN", "surname"},
10963
#endif
10964
    { WC_NID_serialNumber, WC_NAME_SERIAL_NUMBER_OID, oidCertNameType,
10965
      "serialNumber", "serialNumber"},
10966
    { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"},
10967
    { WC_NID_countryName, WC_NAME_COUNTRY_NAME_OID, oidCertNameType,
10968
      "C", "countryName"},
10969
    { WC_NID_localityName, WC_NAME_LOCALITY_NAME_OID, oidCertNameType,
10970
      "L", "localityName"},
10971
    { WC_NID_stateOrProvinceName, WC_NAME_STATE_NAME_OID, oidCertNameType,
10972
      "ST", "stateOrProvinceName"},
10973
    { WC_NID_streetAddress, WC_NAME_STREET_ADDRESS_OID, oidCertNameType,
10974
      "street", "streetAddress"},
10975
    { WC_NID_organizationName, WC_NAME_ORGANIZATION_NAME_OID, oidCertNameType,
10976
      "O", "organizationName"},
10977
    { WC_NID_organizationalUnitName, WC_NAME_ORGANIZATION_UNIT_NAME_OID,
10978
      oidCertNameType, "OU", "organizationalUnitName"},
10979
    { WC_NID_title, WC_NAME_TITLE_OID, oidCertNameType, "title", "title"},
10980
    { WC_NID_description, WC_NAME_DESCRIPTION_OID, oidCertNameType,
10981
      "description", "description"},
10982
    { WC_NID_emailAddress, WC_NAME_EMAIL_ADDRESS_OID, oidCertNameType,
10983
      "emailAddress", "emailAddress"},
10984
    { WC_NID_domainComponent, WC_NAME_DOMAIN_COMPONENT_OID, oidCertNameType,
10985
      "DC", "domainComponent"},
10986
    { WC_NID_rfc822Mailbox, WC_NAME_RFC822_MAILBOX_OID, oidCertNameType,
10987
      "rfc822Mailbox", "rfc822Mailbox"},
10988
    { WC_NID_favouriteDrink, WC_NAME_FAVOURITE_DRINK_OID, oidCertNameType,
10989
      "favouriteDrink", "favouriteDrink"},
10990
    { WC_NID_businessCategory, WC_NAME_BUSINESS_CATEGORY_OID, oidCertNameType,
10991
      "businessCategory", "businessCategory"},
10992
    { WC_NID_jurisdictionCountryName, WC_NAME_JURIS_COUNTRY_OID,
10993
      oidCertNameType, "jurisdictionC", "jurisdictionCountryName"},
10994
    { WC_NID_jurisdictionStateOrProvinceName, WC_NAME_JURIS_STATE_PROV_OID,
10995
      oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"},
10996
    { WC_NID_postalCode, WC_NAME_POSTAL_CODE_OID, oidCertNameType, "postalCode",
10997
      "postalCode"},
10998
    { WC_NID_userId, WC_NAME_USER_ID_OID, oidCertNameType, "UID", "userId"},
10999
    { WC_NID_netscape_cert_type, NETSCAPE_CT_OID, oidCertNameType,
11000
      "nsCertType", "Netscape Cert Type"},
11001
11002
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL)
11003
    { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID,
11004
            oidCsrAttrType, "challengePassword", "challengePassword"},
11005
    { WC_NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID,
11006
        oidCsrAttrType, "contentType", "contentType" },
11007
    { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID,
11008
        oidCsrAttrType, "unstructuredName", "unstructuredName" },
11009
    { WC_NID_name, WC_NAME_NAME_OID, oidCsrAttrType, "name", "name" },
11010
    { WC_NID_surname, SURNAME_OID,
11011
        oidCsrAttrType, "surname", "surname" },
11012
    { WC_NID_givenName, WC_NAME_GIVEN_NAME_OID,
11013
        oidCsrAttrType, "givenName", "givenName" },
11014
    { WC_NID_initials, WC_NAME_INITIALIS_OID,
11015
        oidCsrAttrType, "initials", "initials" },
11016
    { WC_NID_dnQualifier, DNQUALIFIER_OID,
11017
        oidCsrAttrType, "dnQualifer", "dnQualifier" },
11018
#endif
11019
#endif
11020
#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */
11021
        /* oidHashType */
11022
    #ifdef WOLFSSL_MD2
11023
        { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"},
11024
    #endif
11025
    #ifndef NO_MD4
11026
        { WC_NID_md4, MD4h, oidHashType, "MD4", "md4"},
11027
    #endif
11028
    #ifndef NO_MD5
11029
        { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"},
11030
    #endif
11031
    #ifndef NO_SHA
11032
        { WC_NID_sha1, SHAh, oidHashType, "SHA1", "sha1"},
11033
    #endif
11034
    #ifdef WOLFSSL_SHA224
11035
        { WC_NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"},
11036
    #endif
11037
    #ifndef NO_SHA256
11038
        { WC_NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"},
11039
    #endif
11040
    #ifdef WOLFSSL_SHA384
11041
        { WC_NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"},
11042
    #endif
11043
    #ifdef WOLFSSL_SHA512
11044
        { WC_NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"},
11045
    #endif
11046
    #ifdef WOLFSSL_SHA3
11047
        #ifndef WOLFSSL_NOSHA3_224
11048
        { WC_NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"},
11049
        #endif
11050
        #ifndef WOLFSSL_NOSHA3_256
11051
        { WC_NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"},
11052
        #endif
11053
        #ifndef WOLFSSL_NOSHA3_384
11054
        { WC_NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"},
11055
        #endif
11056
        #ifndef WOLFSSL_NOSHA3_512
11057
        { WC_NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"},
11058
        #endif
11059
    #endif /* WOLFSSL_SHA3 */
11060
    #ifdef WOLFSSL_SM3
11061
        { WC_NID_sm3, SM3h, oidHashType, "SM3", "sm3"},
11062
    #endif
11063
    #ifdef WOLFSSL_SHAKE128
11064
        { WC_NID_shake128, SHAKE128h, oidHashType, "SHAKE128", "shake128"},
11065
    #endif
11066
    #ifdef WOLFSSL_SHAKE256
11067
        { WC_NID_shake256, SHAKE256h, oidHashType, "SHAKE256", "shake256"},
11068
    #endif
11069
        /* oidSigType */
11070
    #ifndef NO_DSA
11071
        #ifndef NO_SHA
11072
        { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType,
11073
          "DSA-SHA1", "dsaWithSHA1"},
11074
        { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256",
11075
          "dsa_with_SHA256"},
11076
        #endif
11077
    #endif /* NO_DSA */
11078
    #ifndef NO_RSA
11079
        #ifdef WOLFSSL_MD2
11080
        { WC_NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2",
11081
          "md2WithRSAEncryption"},
11082
        #endif
11083
        #ifndef NO_MD5
11084
        { WC_NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5",
11085
          "md5WithRSAEncryption"},
11086
        #endif
11087
        #ifndef NO_SHA
11088
        { WC_NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1",
11089
          "sha1WithRSAEncryption"},
11090
        #endif
11091
        #ifdef WOLFSSL_SHA224
11092
        { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType,
11093
          "RSA-SHA224", "sha224WithRSAEncryption"},
11094
        #endif
11095
        #ifndef NO_SHA256
11096
        { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType,
11097
          "RSA-SHA256", "sha256WithRSAEncryption"},
11098
        #endif
11099
        #ifdef WOLFSSL_SHA384
11100
        { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType,
11101
          "RSA-SHA384", "sha384WithRSAEncryption"},
11102
        #endif
11103
        #ifdef WOLFSSL_SHA512
11104
        { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType,
11105
          "RSA-SHA512", "sha512WithRSAEncryption"},
11106
        #endif
11107
        #ifdef WOLFSSL_SHA3
11108
        #ifndef WOLFSSL_NOSHA3_224
11109
        { WC_NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224",
11110
          "sha3-224WithRSAEncryption"},
11111
        #endif
11112
        #ifndef WOLFSSL_NOSHA3_256
11113
        { WC_NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256",
11114
          "sha3-256WithRSAEncryption"},
11115
        #endif
11116
        #ifndef WOLFSSL_NOSHA3_384
11117
        { WC_NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384",
11118
          "sha3-384WithRSAEncryption"},
11119
        #endif
11120
        #ifndef WOLFSSL_NOSHA3_512
11121
        { WC_NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512",
11122
          "sha3-512WithRSAEncryption"},
11123
        #endif
11124
        #endif
11125
        #ifdef WC_RSA_PSS
11126
        { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType,
11127
          "RSASSA-PSS", "rsassaPss" },
11128
        #endif
11129
    #endif /* NO_RSA */
11130
    #ifdef HAVE_ECC
11131
        #ifndef NO_SHA
11132
        { WC_NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1",
11133
          "shaWithECDSA"},
11134
        #endif
11135
        #ifdef WOLFSSL_SHA224
11136
        { WC_NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType,
11137
          "ecdsa-with-SHA224","sha224WithECDSA"},
11138
        #endif
11139
        #ifndef NO_SHA256
11140
        { WC_NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType,
11141
          "ecdsa-with-SHA256","sha256WithECDSA"},
11142
        #endif
11143
        #ifdef WOLFSSL_SHA384
11144
        { WC_NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType,
11145
          "ecdsa-with-SHA384","sha384WithECDSA"},
11146
        #endif
11147
        #ifdef WOLFSSL_SHA512
11148
        { WC_NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType,
11149
          "ecdsa-with-SHA512","sha512WithECDSA"},
11150
        #endif
11151
        #ifdef WOLFSSL_SHA3
11152
        #ifndef WOLFSSL_NOSHA3_224
11153
        { WC_NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType,
11154
          "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"},
11155
        #endif
11156
        #ifndef WOLFSSL_NOSHA3_256
11157
        { WC_NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType,
11158
          "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"},
11159
        #endif
11160
        #ifndef WOLFSSL_NOSHA3_384
11161
        { WC_NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType,
11162
          "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"},
11163
        #endif
11164
        #ifndef WOLFSSL_NOSHA3_512
11165
        { WC_NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType,
11166
          "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"},
11167
        #endif
11168
        #endif
11169
    #endif /* HAVE_ECC */
11170
11171
        /* oidKeyType */
11172
    #ifndef NO_DSA
11173
        { WC_NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"},
11174
    #endif /* NO_DSA */
11175
    #ifndef NO_RSA
11176
        { WC_NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption",
11177
          "rsaEncryption"},
11178
    #ifdef WC_RSA_PSS
11179
        { WC_NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"},
11180
    #endif
11181
    #endif /* NO_RSA */
11182
    #ifdef HAVE_ECC
11183
        { WC_NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey",
11184
                                                        "id-ecPublicKey"},
11185
    #endif /* HAVE_ECC */
11186
    #ifndef NO_DH
11187
        { WC_NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement",
11188
          "dhKeyAgreement"},
11189
    #endif
11190
    #ifdef HAVE_ED448
11191
        { WC_NID_ED448, ED448k,  oidKeyType, "ED448", "ED448"},
11192
    #endif
11193
    #ifdef HAVE_ED25519
11194
        { WC_NID_ED25519, ED25519k,  oidKeyType, "ED25519", "ED25519"},
11195
    #endif
11196
    #ifdef HAVE_FALCON
11197
        { CTC_FALCON_LEVEL1, FALCON_LEVEL1k,  oidKeyType, "Falcon Level 1",
11198
                                                          "Falcon Level 1"},
11199
        { CTC_FALCON_LEVEL5, FALCON_LEVEL5k,  oidKeyType, "Falcon Level 5",
11200
                                                          "Falcon Level 5"},
11201
    #endif /* HAVE_FALCON */
11202
    #ifdef WOLFSSL_HAVE_MLDSA
11203
    #ifdef WOLFSSL_MLDSA_FIPS204_DRAFT
11204
        /* Pre-standardization (NIST PQC round 3) Dilithium OID labels.
11205
         * These coexist with the FIPS 204 "ML-DSA 44/65/87" entries below
11206
         * and are intentionally kept under the Dilithium name. */
11207
        { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k,  oidKeyType,
11208
          "Dilithium Level 2", "Dilithium Level 2"},
11209
        { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k,  oidKeyType,
11210
          "Dilithium Level 3", "Dilithium Level 3"},
11211
        { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k,  oidKeyType,
11212
          "Dilithium Level 5", "Dilithium Level 5"},
11213
    #endif /* WOLFSSL_MLDSA_FIPS204_DRAFT */
11214
        { CTC_ML_DSA_44, ML_DSA_44k,  oidKeyType,
11215
          "ML-DSA 44", "ML-DSA 44"},
11216
        { CTC_ML_DSA_65, ML_DSA_65k,  oidKeyType,
11217
          "ML-DSA 65", "ML-DSA 65"},
11218
        { CTC_ML_DSA_87, ML_DSA_87k,  oidKeyType,
11219
          "ML-DSA 87", "ML-DSA 87"},
11220
    #endif /* WOLFSSL_HAVE_MLDSA */
11221
11222
        /* oidCurveType */
11223
    #ifdef HAVE_ECC
11224
        { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType,
11225
          "prime192v1", "prime192v1"},
11226
        { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType,
11227
          "prime192v2", "prime192v2"},
11228
        { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType,
11229
          "prime192v3", "prime192v3"},
11230
11231
        { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType,
11232
          "prime239v1", "prime239v1"},
11233
        { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType,
11234
          "prime239v2", "prime239v2"},
11235
        { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType,
11236
          "prime239v3", "prime239v3"},
11237
11238
        { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType,
11239
          "prime256v1", "prime256v1"},
11240
11241
        { WC_NID_secp112r1, ECC_SECP112R1_OID,  oidCurveType, "secp112r1",
11242
          "secp112r1"},
11243
        { WC_NID_secp112r2, ECC_SECP112R2_OID,  oidCurveType, "secp112r2",
11244
          "secp112r2"},
11245
11246
        { WC_NID_secp128r1, ECC_SECP128R1_OID,  oidCurveType, "secp128r1",
11247
          "secp128r1"},
11248
        { WC_NID_secp128r2, ECC_SECP128R2_OID,  oidCurveType, "secp128r2",
11249
          "secp128r2"},
11250
11251
        { WC_NID_secp160r1, ECC_SECP160R1_OID,  oidCurveType, "secp160r1",
11252
          "secp160r1"},
11253
        { WC_NID_secp160r2, ECC_SECP160R2_OID,  oidCurveType, "secp160r2",
11254
          "secp160r2"},
11255
11256
        { WC_NID_secp224r1, ECC_SECP224R1_OID,  oidCurveType, "secp224r1",
11257
          "secp224r1"},
11258
        { WC_NID_secp384r1, ECC_SECP384R1_OID,  oidCurveType, "secp384r1",
11259
          "secp384r1"},
11260
        { WC_NID_secp521r1, ECC_SECP521R1_OID,  oidCurveType, "secp521r1",
11261
          "secp521r1"},
11262
11263
        { WC_NID_secp160k1, ECC_SECP160K1_OID,  oidCurveType, "secp160k1",
11264
          "secp160k1"},
11265
        { WC_NID_secp192k1, ECC_SECP192K1_OID,  oidCurveType, "secp192k1",
11266
          "secp192k1"},
11267
        { WC_NID_secp224k1, ECC_SECP224K1_OID,  oidCurveType, "secp224k1",
11268
          "secp224k1"},
11269
        { WC_NID_secp256k1, ECC_SECP256K1_OID,  oidCurveType, "secp256k1",
11270
          "secp256k1"},
11271
11272
        { WC_NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID,  oidCurveType,
11273
          "brainpoolP160r1", "brainpoolP160r1"},
11274
        { WC_NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID,  oidCurveType,
11275
          "brainpoolP192r1", "brainpoolP192r1"},
11276
        { WC_NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID,  oidCurveType,
11277
          "brainpoolP224r1", "brainpoolP224r1"},
11278
        { WC_NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID,  oidCurveType,
11279
          "brainpoolP256r1", "brainpoolP256r1"},
11280
        { WC_NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID,  oidCurveType,
11281
          "brainpoolP320r1", "brainpoolP320r1"},
11282
        { WC_NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID,  oidCurveType,
11283
          "brainpoolP384r1", "brainpoolP384r1"},
11284
        { WC_NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID,  oidCurveType,
11285
          "brainpoolP512r1", "brainpoolP512r1"},
11286
11287
    #ifdef WOLFSSL_SM2
11288
        { WC_NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"},
11289
    #endif
11290
    #endif /* HAVE_ECC */
11291
11292
        /* oidBlkType */
11293
    #ifdef WOLFSSL_AES_128
11294
        { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"},
11295
    #endif
11296
    #ifdef WOLFSSL_AES_192
11297
        { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"},
11298
    #endif
11299
    #ifdef WOLFSSL_AES_256
11300
        { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"},
11301
    #endif
11302
    #ifndef NO_DES3
11303
        { WC_NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"},
11304
        { WC_NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"},
11305
    #endif /* !NO_DES3 */
11306
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
11307
        { WC_NID_chacha20_poly1305, WC_NID_chacha20_poly1305, oidBlkType,
11308
          "ChaCha20-Poly1305", "chacha20-poly1305"},
11309
    #endif
11310
11311
        /* oidOcspType */
11312
    #ifdef HAVE_OCSP
11313
        { WC_NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType,
11314
          "basicOCSPResponse", "Basic OCSP Response"},
11315
        { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"},
11316
    #endif /* HAVE_OCSP */
11317
11318
    #ifndef NO_PWDBASED
11319
        /* oidKdfType */
11320
        { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"},
11321
11322
        /* oidPBEType */
11323
        { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType,
11324
          "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"},
11325
        { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES",
11326
          "pbeWithSHA1AndDES-CBC"},
11327
        { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES",
11328
          "pbeWithSHA1And3-KeyTripleDES-CBC"},
11329
    #endif
11330
11331
        /* oidKeyWrapType */
11332
    #ifdef WOLFSSL_AES_128
11333
        { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap",
11334
          "aes128-wrap"},
11335
    #endif
11336
    #ifdef WOLFSSL_AES_192
11337
        { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap",
11338
          "aes192-wrap"},
11339
    #endif
11340
    #ifdef WOLFSSL_AES_256
11341
        { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap",
11342
          "aes256-wrap"},
11343
    #endif
11344
11345
    #ifndef NO_PKCS7
11346
        #ifndef NO_DH
11347
        /* oidCmsKeyAgreeType */
11348
            #ifndef NO_SHA
11349
        { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme,
11350
          oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme",
11351
          "dhSinglePass-stdDH-sha1kdf-scheme"},
11352
            #endif
11353
            #ifdef WOLFSSL_SHA224
11354
        { dhSinglePass_stdDH_sha224kdf_scheme,
11355
          dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType,
11356
          "dhSinglePass-stdDH-sha224kdf-scheme",
11357
          "dhSinglePass-stdDH-sha224kdf-scheme"},
11358
            #endif
11359
            #ifndef NO_SHA256
11360
        { dhSinglePass_stdDH_sha256kdf_scheme,
11361
          dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType,
11362
          "dhSinglePass-stdDH-sha256kdf-scheme",
11363
          "dhSinglePass-stdDH-sha256kdf-scheme"},
11364
            #endif
11365
            #ifdef WOLFSSL_SHA384
11366
        { dhSinglePass_stdDH_sha384kdf_scheme,
11367
          dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType,
11368
          "dhSinglePass-stdDH-sha384kdf-scheme",
11369
          "dhSinglePass-stdDH-sha384kdf-scheme"},
11370
            #endif
11371
            #ifdef WOLFSSL_SHA512
11372
        { dhSinglePass_stdDH_sha512kdf_scheme,
11373
          dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType,
11374
          "dhSinglePass-stdDH-sha512kdf-scheme",
11375
          "dhSinglePass-stdDH-sha512kdf-scheme"},
11376
            #endif
11377
        #endif
11378
    #endif
11379
    #if defined(WOLFSSL_APACHE_HTTPD)
11380
        /* "1.3.6.1.5.5.7.8.7" */
11381
        { WC_NID_id_on_dnsSRV, WOLFSSL_DNS_SRV_SUM, oidCertNameType,
11382
            WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV },
11383
11384
        /* "1.3.6.1.4.1.311.20.2.3" */
11385
        { WC_NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN,
11386
            WOLFSSL_LN_MS_UPN },
11387
11388
        /* "1.3.6.1.5.5.7.1.24" */
11389
        { WC_NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType,
11390
            WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE },
11391
    #endif
11392
#endif /* OPENSSL_EXTRA */
11393
};
11394
11395
#define WOLFSSL_OBJECT_INFO_SZ \
11396
                (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info))
11397
const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ;
11398
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11399
11400
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
11401
/* Free the dynamically allocated data.
11402
 *
11403
 * p  Pointer to dynamically allocated memory.
11404
 */
11405
void wolfSSL_OPENSSL_free(void* p)
11406
{
11407
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
11408
11409
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
11410
}
11411
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11412
11413
#ifdef OPENSSL_EXTRA
11414
11415
void *wolfSSL_OPENSSL_malloc(size_t a)
11416
{
11417
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
11418
}
11419
11420
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
11421
{
11422
    /* 'char' is unsigned on some platforms. */
11423
    return (int)(signed char)HexCharToByte((char)c);
11424
}
11425
11426
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
11427
{
11428
    unsigned char* targetBuf;
11429
    int srcDigitHigh = 0;
11430
    int srcDigitLow = 0;
11431
    size_t srcLen;
11432
    size_t srcIdx = 0;
11433
    long targetIdx = 0;
11434
11435
    srcLen = XSTRLEN(str);
11436
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
11437
    if (targetBuf == NULL) {
11438
        return NULL;
11439
    }
11440
11441
    while (srcIdx < srcLen) {
11442
        if (str[srcIdx] == ':') {
11443
            srcIdx++;
11444
            continue;
11445
        }
11446
11447
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
11448
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
11449
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
11450
            WOLFSSL_MSG("Invalid hex character.");
11451
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
11452
            return NULL;
11453
        }
11454
11455
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
11456
                                                  srcDigitLow       );
11457
    }
11458
11459
    if (len != NULL)
11460
        *len = targetIdx;
11461
11462
    return targetBuf;
11463
}
11464
11465
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
11466
{
11467
    (void)opts;
11468
    (void)settings;
11469
    return wolfSSL_library_init();
11470
}
11471
11472
int wolfSSL_OPENSSL_init_crypto(word64 opts,
11473
    const WOLFSSL_INIT_SETTINGS* settings)
11474
{
11475
    (void)opts;
11476
    (void)settings;
11477
    return wolfSSL_library_init();
11478
}
11479
11480
#endif /* OPENSSL_EXTRA */
11481
11482
11483
#ifdef HAVE_FUZZER
11484
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
11485
{
11486
    if (ssl) {
11487
        ssl->fuzzerCb  = cbf;
11488
        ssl->fuzzerCtx = fCtx;
11489
    }
11490
}
11491
#endif
11492
11493
#ifndef NO_CERTS
11494
#ifdef  HAVE_PK_CALLBACKS
11495
11496
/* callback for premaster secret generation */
11497
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
11498
{
11499
    if (ctx)
11500
        ctx->GenPreMasterCb = cb;
11501
}
11502
/* Set premaster secret generation callback context */
11503
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
11504
{
11505
    if (ssl)
11506
        ssl->GenPreMasterCtx = ctx;
11507
}
11508
/* Get premaster secret generation callback context */
11509
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
11510
{
11511
    if (ssl)
11512
        return ssl->GenPreMasterCtx;
11513
11514
    return NULL;
11515
}
11516
11517
/* callback for master secret generation */
11518
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
11519
    CallbackGenMasterSecret cb)
11520
{
11521
    if (ctx)
11522
        ctx->GenMasterCb = cb;
11523
}
11524
/* Set master secret generation callback context */
11525
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
11526
{
11527
    if (ssl)
11528
        ssl->GenMasterCtx = ctx;
11529
}
11530
/* Get master secret generation callback context */
11531
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
11532
{
11533
    if (ssl)
11534
        return ssl->GenMasterCtx;
11535
11536
    return NULL;
11537
}
11538
11539
/* callback for extended master secret generation */
11540
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
11541
    CallbackGenExtMasterSecret cb)
11542
{
11543
    if (ctx)
11544
        ctx->GenExtMasterCb = cb;
11545
}
11546
/* Set extended master secret generation callback context */
11547
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
11548
{
11549
    if (ssl)
11550
        ssl->GenExtMasterCtx = ctx;
11551
}
11552
/* Get extended master secret generation callback context */
11553
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
11554
{
11555
    if (ssl)
11556
        return ssl->GenExtMasterCtx;
11557
11558
    return NULL;
11559
}
11560
11561
11562
/* callback for session key generation */
11563
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
11564
{
11565
    if (ctx)
11566
        ctx->GenSessionKeyCb = cb;
11567
}
11568
/* Set session key generation callback context */
11569
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
11570
{
11571
    if (ssl)
11572
        ssl->GenSessionKeyCtx = ctx;
11573
}
11574
/* Get session key generation callback context */
11575
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
11576
{
11577
    if (ssl)
11578
        return ssl->GenSessionKeyCtx;
11579
11580
    return NULL;
11581
}
11582
11583
/* callback for setting encryption keys */
11584
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
11585
{
11586
    if (ctx)
11587
        ctx->EncryptKeysCb = cb;
11588
}
11589
/* Set encryption keys callback context */
11590
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
11591
{
11592
    if (ssl)
11593
        ssl->EncryptKeysCtx = ctx;
11594
}
11595
/* Get encryption keys callback context */
11596
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
11597
{
11598
    if (ssl)
11599
        return ssl->EncryptKeysCtx;
11600
11601
    return NULL;
11602
}
11603
11604
/* callback for Tls finished */
11605
/* the callback can be used to build TLS Finished message if enabled */
11606
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
11607
{
11608
    if (ctx)
11609
        ctx->TlsFinishedCb = cb;
11610
}
11611
/* Set Tls finished callback context */
11612
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
11613
{
11614
    if (ssl)
11615
        ssl->TlsFinishedCtx = ctx;
11616
}
11617
/* Get Tls finished callback context */
11618
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
11619
{
11620
    if (ssl)
11621
        return ssl->TlsFinishedCtx;
11622
11623
    return NULL;
11624
}
11625
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
11626
/* callback for verify data */
11627
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
11628
{
11629
    if (ctx)
11630
        ctx->VerifyMacCb = cb;
11631
}
11632
11633
/* Set set keys callback context */
11634
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
11635
{
11636
    if (ssl)
11637
        ssl->VerifyMacCtx = ctx;
11638
}
11639
/* Get set  keys callback context */
11640
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
11641
{
11642
    if (ssl)
11643
        return ssl->VerifyMacCtx;
11644
11645
    return NULL;
11646
}
11647
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
11648
11649
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
11650
                                      CallbackHKDFExpandLabel cb)
11651
{
11652
    if (ctx)
11653
        ctx->HKDFExpandLabelCb = cb;
11654
}
11655
#ifdef WOLFSSL_PUBLIC_ASN
11656
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
11657
                                        CallbackProcessPeerCert cb)
11658
{
11659
    if (ctx)
11660
        ctx->ProcessPeerCertCb = cb;
11661
}
11662
#endif /* WOLFSSL_PUBLIC_ASN */
11663
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
11664
                                       CallbackProcessServerSigKex cb)
11665
{
11666
    if (ctx)
11667
        ctx->ProcessServerSigKexCb = cb;
11668
}
11669
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
11670
                                          CallbackPerformTlsRecordProcessing cb)
11671
{
11672
    if (ctx)
11673
        ctx->PerformTlsRecordProcessingCb = cb;
11674
}
11675
#endif /* HAVE_PK_CALLBACKS */
11676
#endif /* NO_CERTS */
11677
11678
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
11679
11680
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
11681
{
11682
    if (ctx)
11683
        ctx->HkdfExtractCb = cb;
11684
}
11685
11686
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
11687
{
11688
    if (ssl)
11689
        ssl->HkdfExtractCtx = ctx;
11690
}
11691
11692
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
11693
{
11694
    if (ssl)
11695
        return ssl->HkdfExtractCtx;
11696
11697
    return NULL;
11698
}
11699
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
11700
11701
#ifdef WOLFSSL_HAVE_WOLFSCEP
11702
    /* Used by autoconf to see if wolfSCEP is available */
11703
    void wolfSSL_wolfSCEP(void) {}
11704
#endif
11705
11706
11707
#ifdef WOLFSSL_HAVE_CERT_SERVICE
11708
    /* Used by autoconf to see if cert service is available */
11709
    void wolfSSL_cert_service(void) {}
11710
#endif
11711
11712
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
11713
    !defined(WOLFCRYPT_ONLY)
11714
11715
    /* NID variables are dependent on compatibility header files currently
11716
     *
11717
     * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL
11718
     *         on fail
11719
     */
11720
11721
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id)
11722
    {
11723
        return wolfSSL_OBJ_nid2obj_ex(id, NULL);
11724
    }
11725
11726
11727
    WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id,
11728
                                                WOLFSSL_ASN1_OBJECT* arg_obj)
11729
    {
11730
        word32 oidSz = 0;
11731
        int nid = 0;
11732
        const byte* oid;
11733
        word32 type = 0;
11734
        WOLFSSL_ASN1_OBJECT* obj = arg_obj;
11735
        byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */
11736
        word32 objSz = 0;
11737
        const char* sName = NULL;
11738
        int i;
11739
11740
#ifdef WOLFSSL_DEBUG_OPENSSL
11741
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj");
11742
#endif
11743
11744
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
11745
            if (wolfssl_object_info[i].nid == id) {
11746
                nid = id;
11747
                id = wolfssl_object_info[i].id;
11748
                sName = wolfssl_object_info[i].sName;
11749
                type = wolfssl_object_info[i].type;
11750
                break;
11751
            }
11752
        }
11753
        if (i == (int)WOLFSSL_OBJECT_INFO_SZ) {
11754
            WOLFSSL_MSG("NID not in table");
11755
        #ifdef WOLFSSL_QT
11756
            sName = NULL;
11757
            type = (word32)id;
11758
        #else
11759
            return NULL;
11760
        #endif
11761
        }
11762
11763
    #ifdef HAVE_ECC
11764
         if (type == 0 && wc_ecc_get_oid((word32)id, &oid, &oidSz) > 0) {
11765
             type = oidCurveType;
11766
         }
11767
    #endif /* HAVE_ECC */
11768
11769
        if (sName != NULL) {
11770
            if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) {
11771
                WOLFSSL_MSG("Attempted short name is too large");
11772
                return NULL;
11773
            }
11774
        }
11775
11776
        oid = OidFromId((word32)id, type, &oidSz);
11777
11778
        /* set object ID to buffer */
11779
        if (obj == NULL){
11780
            obj = wolfSSL_ASN1_OBJECT_new();
11781
            if (obj == NULL) {
11782
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
11783
                return NULL;
11784
            }
11785
        }
11786
        obj->nid     = nid;
11787
        obj->type    = id;
11788
        obj->grp     = (int)type;
11789
11790
        obj->sName[0] = '\0';
11791
        if (sName != NULL) {
11792
            XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName));
11793
        }
11794
11795
        objBuf[0] = ASN_OBJECT_ID; objSz++;
11796
        objSz += SetLength(oidSz, objBuf + 1);
11797
        if (oidSz) {
11798
            XMEMCPY(objBuf + objSz, oid, oidSz);
11799
            objSz     += oidSz;
11800
        }
11801
11802
        if (obj->objSz == 0 || objSz != obj->objSz) {
11803
            obj->objSz = objSz;
11804
            if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) ||
11805
                                                           (obj->obj == NULL)) {
11806
                if (obj->obj != NULL)
11807
                    XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1);
11808
                obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
11809
                if (obj->obj == NULL) {
11810
                    wolfSSL_ASN1_OBJECT_free(obj);
11811
                    return NULL;
11812
                }
11813
                obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
11814
            }
11815
            else {
11816
                obj->dynamic &= (unsigned char)~WOLFSSL_ASN1_DYNAMIC_DATA;
11817
            }
11818
        }
11819
        XMEMCPY((byte*)obj->obj, objBuf, obj->objSz);
11820
11821
        (void)type;
11822
11823
        return obj;
11824
    }
11825
11826
    static const char* oid_translate_num_to_str(const char* oid)
11827
    {
11828
        const struct oid_dict {
11829
            const char* num;
11830
            const char* desc;
11831
        } oid_dict[] = {
11832
            { "2.5.29.37.0",       "Any Extended Key Usage" },
11833
            { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" },
11834
            { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" },
11835
            { "1.3.6.1.5.5.7.3.3", "Code Signing" },
11836
            { "1.3.6.1.5.5.7.3.4", "E-mail Protection" },
11837
            { "1.3.6.1.5.5.7.3.8", "Time Stamping" },
11838
            { "1.3.6.1.5.5.7.3.9", "OCSP Signing" },
11839
            { NULL, NULL }
11840
        };
11841
        const struct oid_dict* idx;
11842
11843
        for (idx = oid_dict; idx->num != NULL; idx++) {
11844
            if (!XSTRCMP(oid, idx->num)) {
11845
                return idx->desc;
11846
            }
11847
        }
11848
        return NULL;
11849
    }
11850
11851
    static int wolfssl_obj2txt_numeric(char *buf, int bufLen,
11852
                                       const WOLFSSL_ASN1_OBJECT *a)
11853
    {
11854
        int bufSz;
11855
        int    length;
11856
        word32 idx = 0;
11857
        byte   tag;
11858
11859
        if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) {
11860
            return WOLFSSL_FAILURE;
11861
        }
11862
11863
        if (tag != ASN_OBJECT_ID) {
11864
            WOLFSSL_MSG("Bad ASN1 Object");
11865
            return WOLFSSL_FAILURE;
11866
        }
11867
11868
        if (GetLength((const byte*)a->obj, &idx, &length,
11869
                       a->objSz) < 0 || length < 0) {
11870
            return ASN_PARSE_E;
11871
        }
11872
11873
        if (bufLen < MAX_OID_STRING_SZ) {
11874
            bufSz = bufLen - 1;
11875
        }
11876
        else {
11877
            bufSz = MAX_OID_STRING_SZ;
11878
        }
11879
11880
        if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx,
11881
                    (word32)length)) <= 0) {
11882
            WOLFSSL_MSG("Error decoding OID");
11883
            return WOLFSSL_FAILURE;
11884
        }
11885
11886
        buf[bufSz] = '\0';
11887
11888
        return bufSz;
11889
    }
11890
11891
    /* If no_name is one then use numerical form, otherwise short name.
11892
     *
11893
     * Returns the buffer size on success, WOLFSSL_FAILURE on error
11894
     */
11895
    int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a,
11896
                            int no_name)
11897
    {
11898
        int bufSz;
11899
        const char* desc;
11900
        const char* name;
11901
11902
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt");
11903
11904
        if (buf == NULL || bufLen <= 1 || a == NULL) {
11905
            WOLFSSL_MSG("Bad input argument");
11906
            return WOLFSSL_FAILURE;
11907
        }
11908
11909
        if (no_name == 1) {
11910
            return wolfssl_obj2txt_numeric(buf, bufLen, a);
11911
        }
11912
11913
        /* return long name unless using x509small, then return short name */
11914
#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA)
11915
        name = a->sName;
11916
#else
11917
        name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a));
11918
#endif
11919
11920
        if (name == NULL) {
11921
            WOLFSSL_MSG("Name not found");
11922
            bufSz = 0;
11923
        }
11924
        else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) {
11925
            bufSz = (int)XSTRLEN(name);
11926
        }
11927
        else {
11928
            bufSz = bufLen - 1;
11929
        }
11930
        if (bufSz) {
11931
            XMEMCPY(buf, name, (size_t)bufSz);
11932
        }
11933
        else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL ||
11934
                 a->type == WOLFSSL_GEN_URI) {
11935
            size_t objLen = XSTRLEN((const char*)a->obj);
11936
            if (objLen >= (size_t)bufLen) {
11937
                bufSz = bufLen - 1;
11938
            }
11939
            else {
11940
                bufSz = (int)objLen;
11941
            }
11942
            XMEMCPY(buf, a->obj, (size_t)bufSz);
11943
        }
11944
        else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) {
11945
            if ((desc = oid_translate_num_to_str(buf))) {
11946
                bufSz = (int)XSTRLEN(desc);
11947
                bufSz = (int)min((word32)bufSz,(word32) bufLen - 1);
11948
                XMEMCPY(buf, desc, (size_t)bufSz);
11949
            }
11950
        }
11951
        else {
11952
            bufSz = 0;
11953
        }
11954
11955
        buf[bufSz] = '\0';
11956
11957
        return bufSz;
11958
    }
11959
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11960
11961
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
11962
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
11963
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
11964
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL)
11965
    /* Returns the long name that corresponds with an ASN1_OBJECT nid value.
11966
     *  n : NID value of ASN1_OBJECT to search */
11967
    const char* wolfSSL_OBJ_nid2ln(int n)
11968
    {
11969
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
11970
        size_t i;
11971
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln");
11972
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
11973
            if (obj_info->nid == n) {
11974
                return obj_info->lName;
11975
            }
11976
        }
11977
        WOLFSSL_MSG("NID not found in table");
11978
        return NULL;
11979
    }
11980
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
11981
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */
11982
11983
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
11984
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
11985
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
11986
    defined(WOLFSSL_HAPROXY)
11987
    /* Return the corresponding short name for the nid <n>.
11988
     * or NULL if short name can't be found.
11989
     */
11990
    const char * wolfSSL_OBJ_nid2sn(int n) {
11991
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
11992
        size_t i;
11993
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn");
11994
11995
        if (n == WC_NID_md5) {
11996
            /* WC_NID_surname == WC_NID_md5 and WC_NID_surname comes before WC_NID_md5 in
11997
             * wolfssl_object_info. As a result, the loop below will incorrectly
11998
             * return "SN" instead of "MD5." WC_NID_surname isn't the true OpenSSL
11999
             * NID, but other functions rely on this table and modifying it to
12000
             * conform with OpenSSL's NIDs isn't trivial. */
12001
             return "MD5";
12002
        }
12003
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
12004
            if (obj_info->nid == n) {
12005
                return obj_info->sName;
12006
            }
12007
        }
12008
        WOLFSSL_MSG_EX("SN not found (nid:%d)",n);
12009
        return NULL;
12010
    }
12011
12012
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12013
    int wolfSSL_OBJ_sn2nid(const char *sn) {
12014
        WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid");
12015
        if (sn == NULL)
12016
            return WC_NID_undef;
12017
        return wc_OBJ_sn2nid(sn);
12018
    }
12019
#endif
12020
12021
    size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o)
12022
    {
12023
        size_t ret = 0;
12024
        int err = 0;
12025
        word32 idx = 0;
12026
        int len = 0;
12027
12028
        WOLFSSL_ENTER("wolfSSL_OBJ_length");
12029
12030
        if (o == NULL || o->obj == NULL) {
12031
            WOLFSSL_MSG("Bad argument.");
12032
            err = 1;
12033
        }
12034
12035
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
12036
            WOLFSSL_MSG("Error parsing ASN.1 header.");
12037
            err = 1;
12038
        }
12039
        if (err == 0) {
12040
            ret = (size_t)len;
12041
        }
12042
12043
        WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret);
12044
12045
        return ret;
12046
    }
12047
12048
    const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o)
12049
    {
12050
        const unsigned char* ret = NULL;
12051
        int err = 0;
12052
        word32 idx = 0;
12053
        int len = 0;
12054
12055
        WOLFSSL_ENTER("wolfSSL_OBJ_get0_data");
12056
12057
        if (o == NULL || o->obj == NULL) {
12058
            WOLFSSL_MSG("Bad argument.");
12059
            err = 1;
12060
        }
12061
12062
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
12063
            WOLFSSL_MSG("Error parsing ASN.1 header.");
12064
            err = 1;
12065
        }
12066
        if (err == 0) {
12067
            ret = o->obj + idx;
12068
        }
12069
12070
        return ret;
12071
    }
12072
12073
12074
    /* Gets the NID value that corresponds with the ASN1 object.
12075
     *
12076
     * o ASN1 object to get NID of
12077
     *
12078
     * Return NID on success and a negative value on failure
12079
     */
12080
    int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o)
12081
    {
12082
        word32 oid = 0;
12083
        word32 idx = 0;
12084
        int ret;
12085
12086
#ifdef WOLFSSL_DEBUG_OPENSSL
12087
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid");
12088
#endif
12089
12090
        if (o == NULL) {
12091
            return WOLFSSL_FATAL_ERROR;
12092
        }
12093
12094
        #ifdef WOLFSSL_QT
12095
        if (o->grp == oidCertExtType) {
12096
            /* If nid is an unknown extension, return WC_NID_undef */
12097
            if (wolfSSL_OBJ_nid2sn(o->nid) == NULL)
12098
                return WC_NID_undef;
12099
        }
12100
        #endif
12101
12102
        if (o->nid > 0)
12103
            return o->nid;
12104
        if ((ret = GetObjectId(o->obj, &idx, &oid,
12105
                                    (word32)o->grp, o->objSz)) < 0) {
12106
            if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) {
12107
                /* Put ASN object tag in front and try again */
12108
                int len = SetObjectId((int)o->objSz, NULL) + (int)o->objSz;
12109
                byte* buf = (byte*)XMALLOC((size_t)len, NULL,
12110
                                            DYNAMIC_TYPE_TMP_BUFFER);
12111
                if (!buf) {
12112
                    WOLFSSL_MSG("malloc error");
12113
                    return WOLFSSL_FATAL_ERROR;
12114
                }
12115
                idx = (word32)SetObjectId((int)o->objSz, buf);
12116
                XMEMCPY(buf + idx, o->obj, o->objSz);
12117
                idx = 0;
12118
                ret = GetObjectId(buf, &idx, &oid, (word32)o->grp, (word32)len);
12119
                XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
12120
                if (ret < 0) {
12121
                    WOLFSSL_MSG("Issue getting OID of object");
12122
                    return WOLFSSL_FATAL_ERROR;
12123
                }
12124
            }
12125
            else {
12126
                WOLFSSL_MSG("Issue getting OID of object");
12127
                return WOLFSSL_FATAL_ERROR;
12128
            }
12129
        }
12130
12131
        return oid2nid(oid, o->grp);
12132
    }
12133
12134
    /* Return the corresponding NID for the long name <ln>
12135
     * or WC_NID_undef if NID can't be found.
12136
     */
12137
    int wolfSSL_OBJ_ln2nid(const char *ln)
12138
    {
12139
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
12140
        size_t lnlen;
12141
        WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid");
12142
        if (ln && (lnlen = XSTRLEN(ln)) > 0) {
12143
            /* Accept input like "/commonName=" */
12144
            if (ln[0] == '/') {
12145
                ln++;
12146
                lnlen--;
12147
            }
12148
            if (lnlen) {
12149
                size_t i;
12150
12151
                if (ln[lnlen-1] == '=') {
12152
                    lnlen--;
12153
                }
12154
                for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
12155
                    if (lnlen == XSTRLEN(obj_info->lName) &&
12156
                            XSTRNCMP(ln, obj_info->lName, lnlen) == 0) {
12157
                        return obj_info->nid;
12158
                    }
12159
                }
12160
            }
12161
        }
12162
        return WC_NID_undef;
12163
    }
12164
12165
    /* compares two objects, return 0 if equal */
12166
    int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a,
12167
                        const WOLFSSL_ASN1_OBJECT* b)
12168
    {
12169
        WOLFSSL_ENTER("wolfSSL_OBJ_cmp");
12170
12171
        if (a && b && a->obj && b->obj) {
12172
            if (a->objSz == b->objSz) {
12173
                return XMEMCMP(a->obj, b->obj, a->objSz);
12174
            }
12175
            else if (a->type == EXT_KEY_USAGE_OID ||
12176
                     b->type == EXT_KEY_USAGE_OID) {
12177
                /* Special case for EXT_KEY_USAGE_OID so that
12178
                 * cmp will be treated as a substring search */
12179
                /* Used in libest to check for id-kp-cmcRA in
12180
                 * EXT_KEY_USAGE extension */
12181
                unsigned int idx;
12182
                const byte* s; /* shorter */
12183
                unsigned int sLen;
12184
                const byte* l; /* longer */
12185
                unsigned int lLen;
12186
                if (a->objSz > b->objSz) {
12187
                    s = b->obj; sLen = b->objSz;
12188
                    l = a->obj; lLen = a->objSz;
12189
                }
12190
                else {
12191
                    s = a->obj; sLen = a->objSz;
12192
                    l = b->obj; lLen = b->objSz;
12193
                }
12194
                for (idx = 0; idx <= lLen - sLen; idx++) {
12195
                    if (XMEMCMP(l + idx, s, sLen) == 0) {
12196
                        /* Found substring */
12197
                        return 0;
12198
                    }
12199
                }
12200
            }
12201
        }
12202
12203
        return WOLFSSL_FATAL_ERROR;
12204
    }
12205
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
12206
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */
12207
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
12208
    defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
12209
    defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
12210
    defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
12211
    /* Gets the NID value that is related to the OID string passed in. Example
12212
     * string would be "2.5.29.14" for subject key ID.
12213
     *
12214
     * returns NID value on success and WC_NID_undef on error
12215
     */
12216
    int wolfSSL_OBJ_txt2nid(const char* s)
12217
    {
12218
        unsigned int i;
12219
    #ifdef WOLFSSL_CERT_EXT
12220
        int ret;
12221
        unsigned int sum = 0;
12222
        unsigned int outSz = MAX_OID_SZ;
12223
        unsigned char out[MAX_OID_SZ];
12224
12225
        XMEMSET(out, 0, sizeof(out));
12226
    #endif
12227
12228
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid");
12229
12230
        if (s == NULL) {
12231
            return WC_NID_undef;
12232
        }
12233
12234
    #ifdef WOLFSSL_CERT_EXT
12235
        ret = EncodePolicyOID(out, &outSz, s, NULL);
12236
        if (ret == 0) {
12237
            /* sum OID */
12238
            sum = wc_oid_sum(out, outSz);
12239
        }
12240
    #endif /* WOLFSSL_CERT_EXT */
12241
12242
        /* get the group that the OID's sum is in
12243
         * @TODO possible conflict with multiples */
12244
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
12245
            int len;
12246
        #ifdef WOLFSSL_CERT_EXT
12247
            if (ret == 0) {
12248
                if (wolfssl_object_info[i].id == (int)sum) {
12249
                    return wolfssl_object_info[i].nid;
12250
                }
12251
            }
12252
        #endif
12253
12254
            /* try as a short name */
12255
            len = (int)XSTRLEN(s);
12256
            if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len &&
12257
                XSTRNCMP(wolfssl_object_info[i].sName, s, (word32)len) == 0) {
12258
                return wolfssl_object_info[i].nid;
12259
            }
12260
12261
            /* try as a long name */
12262
            if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len &&
12263
                XSTRNCMP(wolfssl_object_info[i].lName, s, (word32)len) == 0) {
12264
                return wolfssl_object_info[i].nid;
12265
            }
12266
        }
12267
12268
        return WC_NID_undef;
12269
    }
12270
#endif
12271
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
12272
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
12273
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
12274
    defined(WOLFSSL_HAPROXY)
12275
12276
    /* Creates new ASN1_OBJECT from short name, long name, or text
12277
     * representation of oid. If no_name is 0, then short name, long name, and
12278
     * numerical value of oid are interpreted. If no_name is 1, then only the
12279
     * numerical value of the oid is interpreted.
12280
     *
12281
     * Returns pointer to ASN1_OBJECT on success, or NULL on error.
12282
     */
12283
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
12284
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name)
12285
    {
12286
        int i, ret;
12287
        int nid = WC_NID_undef;
12288
        unsigned int outSz = MAX_OID_SZ;
12289
        unsigned char out[MAX_OID_SZ];
12290
        WOLFSSL_ASN1_OBJECT* obj;
12291
12292
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj");
12293
12294
        if (s == NULL)
12295
            return NULL;
12296
12297
        /* If s is numerical value, try to sum oid */
12298
        ret = EncodePolicyOID(out, &outSz, s, NULL);
12299
        if (ret == 0 && outSz > 0) {
12300
            /* If numerical encode succeeded then just
12301
             * create object from that because sums are
12302
             * not unique and can cause confusion. */
12303
            obj = wolfSSL_ASN1_OBJECT_new();
12304
            if (obj == NULL) {
12305
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
12306
                return NULL;
12307
            }
12308
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
12309
            obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL,
12310
                    DYNAMIC_TYPE_ASN1);
12311
            if (obj->obj == NULL) {
12312
                wolfSSL_ASN1_OBJECT_free(obj);
12313
                return NULL;
12314
            }
12315
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
12316
            i = SetObjectId((int)outSz, (byte*)obj->obj);
12317
            XMEMCPY((byte*)obj->obj + i, out, outSz);
12318
            obj->objSz = (word32)i + outSz;
12319
            return obj;
12320
        }
12321
12322
        /* TODO: update short names in wolfssl_object_info and check OID sums
12323
           are correct */
12324
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
12325
            /* Short name, long name, and numerical value are interpreted */
12326
            if (no_name == 0 &&
12327
                ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) ||
12328
                 (XSTRCMP(s, wolfssl_object_info[i].lName) == 0)))
12329
            {
12330
                    nid = wolfssl_object_info[i].nid;
12331
            }
12332
        }
12333
12334
        if (nid != WC_NID_undef)
12335
            return wolfSSL_OBJ_nid2obj(nid);
12336
12337
        return NULL;
12338
    }
12339
#endif
12340
12341
    /* compatibility function. Its intended use is to remove OID's from an
12342
     * internal table that have been added with OBJ_create. wolfSSL manages its
12343
     * own internal OID values and does not currently support OBJ_create. */
12344
    void wolfSSL_OBJ_cleanup(void)
12345
    {
12346
        WOLFSSL_ENTER("wolfSSL_OBJ_cleanup");
12347
    }
12348
12349
    #ifndef NO_WOLFSSL_STUB
12350
    int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln)
12351
    {
12352
        (void)oid;
12353
        (void)sn;
12354
        (void)ln;
12355
        WOLFSSL_STUB("wolfSSL_OBJ_create");
12356
        return WOLFSSL_FAILURE;
12357
    }
12358
    #endif
12359
12360
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
12361
    {
12362
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12363
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
12364
        ssl->options.verifyDepth = (byte)depth;
12365
    #endif
12366
    }
12367
12368
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
12369
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
12370
12371
#ifdef OPENSSL_EXTRA
12372
12373
/* wolfSSL uses negative values for error states. This function returns an
12374
 * unsigned type so the value returned is the absolute value of the error.
12375
 */
12376
unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line)
12377
{
12378
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
12379
12380
    (void)line;
12381
    (void)file;
12382
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
12383
    {
12384
        int ret;
12385
12386
        if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) {
12387
            WOLFSSL_MSG("Issue peeking at error node in queue");
12388
            return 0;
12389
        }
12390
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \
12391
        || defined(WOLFSSL_HAPROXY)
12392
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
12393
            return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
12394
    #endif
12395
    #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
12396
        if (ret == ASN1_R_HEADER_TOO_LONG) {
12397
            return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
12398
        }
12399
    #endif
12400
        return (unsigned long)ret;
12401
    }
12402
#else
12403
    return (unsigned long)(0 - NOT_COMPILED_IN);
12404
#endif
12405
}
12406
12407
#endif /* OPENSSL_EXTRA */
12408
12409
#ifdef HAVE_EX_DATA_CRYPTO
12410
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
12411
12412
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
12413
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
12414
        WOLFSSL_CRYPTO_EX_free* free_func)
12415
{
12416
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
12417
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
12418
    if (new_ctx == NULL)
12419
        return WOLFSSL_FATAL_ERROR;
12420
    new_ctx->ctx_l = ctx_l;
12421
    new_ctx->ctx_ptr = ctx_ptr;
12422
    new_ctx->new_func = new_func;
12423
    new_ctx->free_func = free_func;
12424
    new_ctx->dup_func = dup_func;
12425
    new_ctx->next = NULL;
12426
    /* Push to end of list */
12427
    while (*dst != NULL)
12428
        dst = &(*dst)->next;
12429
    *dst = new_ctx;
12430
    return 0;
12431
}
12432
12433
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
12434
{
12435
    while (cb_ctx != NULL) {
12436
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
12437
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
12438
        cb_ctx = next;
12439
    }
12440
}
12441
12442
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
12443
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
12444
{
12445
    int idx = 0;
12446
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12447
        if (cb_ctx->new_func != NULL)
12448
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
12449
                    cb_ctx->ctx_ptr);
12450
    }
12451
}
12452
12453
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
12454
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
12455
{
12456
    int idx = 0;
12457
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12458
        if (cb_ctx->dup_func != NULL) {
12459
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
12460
            if (!cb_ctx->dup_func(out, in,
12461
                    &ptr, idx,
12462
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
12463
                return WOLFSSL_FAILURE;
12464
            }
12465
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
12466
        }
12467
    }
12468
    return WOLFSSL_SUCCESS;
12469
}
12470
12471
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
12472
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
12473
{
12474
    int idx = 0;
12475
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12476
        if (cb_ctx->free_func != NULL)
12477
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
12478
                    cb_ctx->ctx_ptr);
12479
    }
12480
}
12481
12482
/**
12483
 * wolfssl_local_get_ex_new_index is a helper function for the following
12484
 * xx_get_ex_new_index functions:
12485
 *  - wolfSSL_CRYPTO_get_ex_new_index
12486
 *  - wolfSSL_CTX_get_ex_new_index
12487
 *  - wolfSSL_get_ex_new_index
12488
 * Issues a unique index number for the specified class-index.
12489
 * Returns an index number greater or equal to zero on success,
12490
 * -1 on failure.
12491
 */
12492
int wolfssl_local_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
12493
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
12494
        WOLFSSL_CRYPTO_EX_free* free_func)
12495
{
12496
    /* index counter for each class index*/
12497
    static int ctx_idx = 0;
12498
    static int ssl_idx = 0;
12499
    static int ssl_session_idx = 0;
12500
    static int x509_idx = 0;
12501
12502
    int idx = -1;
12503
12504
    switch(class_index) {
12505
        case WOLF_CRYPTO_EX_INDEX_SSL:
12506
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12507
                    dup_func, free_func);
12508
            idx = ssl_idx++;
12509
            break;
12510
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
12511
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12512
                    dup_func, free_func);
12513
            idx = ctx_idx++;
12514
            break;
12515
        case WOLF_CRYPTO_EX_INDEX_X509:
12516
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12517
                    dup_func, free_func);
12518
            idx = x509_idx++;
12519
            break;
12520
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
12521
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
12522
                    new_func, dup_func, free_func) != 0)
12523
                return WOLFSSL_FATAL_ERROR;
12524
            idx = ssl_session_idx++;
12525
            break;
12526
12527
        /* following class indexes are not supoprted */
12528
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
12529
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
12530
        case WOLF_CRYPTO_EX_INDEX_DH:
12531
        case WOLF_CRYPTO_EX_INDEX_DSA:
12532
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
12533
        case WOLF_CRYPTO_EX_INDEX_RSA:
12534
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
12535
        case WOLF_CRYPTO_EX_INDEX_UI:
12536
        case WOLF_CRYPTO_EX_INDEX_BIO:
12537
        case WOLF_CRYPTO_EX_INDEX_APP:
12538
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
12539
        case WOLF_CRYPTO_EX_INDEX_DRBG:
12540
        default:
12541
            break;
12542
    }
12543
    if (idx >= MAX_EX_DATA)
12544
        return WOLFSSL_FATAL_ERROR;
12545
    return idx;
12546
}
12547
#endif /* HAVE_EX_DATA_CRYPTO */
12548
12549
#ifdef HAVE_EX_DATA_CRYPTO
12550
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
12551
                                 WOLFSSL_CRYPTO_EX_new* new_func,
12552
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
12553
                                 WOLFSSL_CRYPTO_EX_free* free_func)
12554
{
12555
12556
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
12557
12558
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx,
12559
                                    arg, new_func, dup_func, free_func);
12560
}
12561
12562
/* Return the index that can be used for the WOLFSSL structure to store
12563
 * application data.
12564
 *
12565
 */
12566
int wolfSSL_get_ex_new_index(long argValue, void* arg,
12567
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
12568
        WOLFSSL_CRYPTO_EX_free* cb3)
12569
{
12570
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
12571
12572
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue,
12573
            arg, cb1, cb2, cb3);
12574
}
12575
#endif /* HAVE_EX_DATA_CRYPTO */
12576
12577
#ifdef OPENSSL_EXTRA
12578
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
12579
{
12580
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
12581
#ifdef HAVE_EX_DATA
12582
    if (ctx != NULL) {
12583
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
12584
    }
12585
#else
12586
    (void)ctx;
12587
    (void)idx;
12588
#endif
12589
    return NULL;
12590
}
12591
12592
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
12593
{
12594
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
12595
#ifdef HAVE_EX_DATA
12596
    if (ctx != NULL) {
12597
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
12598
    }
12599
#else
12600
    (void)ctx;
12601
    (void)idx;
12602
    (void)data;
12603
#endif
12604
    return WOLFSSL_FAILURE;
12605
}
12606
12607
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
12608
int wolfSSL_CTX_set_ex_data_with_cleanup(
12609
    WOLFSSL_CTX* ctx,
12610
    int idx,
12611
    void* data,
12612
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
12613
{
12614
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
12615
    if (ctx != NULL) {
12616
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
12617
                                                       cleanup_routine);
12618
    }
12619
    return WOLFSSL_FAILURE;
12620
}
12621
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
12622
#endif /* OPENSSL_EXTRA */
12623
12624
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12625
12626
/* Returns char* to app data stored in ex[0].
12627
 *
12628
 * ssl WOLFSSL structure to get app data from
12629
 */
12630
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
12631
{
12632
    /* checkout exdata stuff... */
12633
    WOLFSSL_ENTER("wolfSSL_get_app_data");
12634
12635
    return wolfSSL_get_ex_data(ssl, 0);
12636
}
12637
12638
12639
/* Set ex array 0 to have app data
12640
 *
12641
 * ssl WOLFSSL struct to set app data in
12642
 * arg data to be stored
12643
 *
12644
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
12645
 */
12646
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
12647
    WOLFSSL_ENTER("wolfSSL_set_app_data");
12648
12649
    return wolfSSL_set_ex_data(ssl, 0, arg);
12650
}
12651
12652
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
12653
12654
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
12655
0
{
12656
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
12657
#ifdef HAVE_EX_DATA
12658
    if (ssl != NULL) {
12659
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
12660
    }
12661
#else
12662
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
12663
0
    (void)ssl;
12664
0
    (void)idx;
12665
0
    (void)data;
12666
0
#endif
12667
0
    return WOLFSSL_FAILURE;
12668
0
}
12669
12670
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
12671
int wolfSSL_set_ex_data_with_cleanup(
12672
    WOLFSSL* ssl,
12673
    int idx,
12674
    void* data,
12675
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
12676
{
12677
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
12678
    if (ssl != NULL)
12679
    {
12680
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
12681
                                                       cleanup_routine);
12682
    }
12683
    return WOLFSSL_FAILURE;
12684
}
12685
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
12686
12687
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
12688
0
{
12689
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
12690
#ifdef HAVE_EX_DATA
12691
    if (ssl != NULL) {
12692
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
12693
    }
12694
#else
12695
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
12696
0
    (void)ssl;
12697
0
    (void)idx;
12698
0
#endif
12699
0
    return 0;
12700
0
}
12701
12702
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
12703
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
12704
12705
/* returns the enum value associated with handshake state
12706
 *
12707
 * ssl the WOLFSSL structure to get state of
12708
 */
12709
int wolfSSL_get_state(const WOLFSSL* ssl)
12710
{
12711
    WOLFSSL_ENTER("wolfSSL_get_state");
12712
12713
    if (ssl == NULL) {
12714
        WOLFSSL_MSG("Null argument passed in");
12715
        return WOLFSSL_FAILURE;
12716
    }
12717
12718
    return ssl->options.handShakeState;
12719
}
12720
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
12721
12722
#ifdef OPENSSL_EXTRA
12723
void wolfSSL_certs_clear(WOLFSSL* ssl)
12724
{
12725
    WOLFSSL_ENTER("wolfSSL_certs_clear");
12726
12727
    if (ssl == NULL)
12728
        return;
12729
12730
    /* ctx still owns certificate, certChain, key, dh, and cm */
12731
    if (ssl->buffers.weOwnCert) {
12732
        FreeDer(&ssl->buffers.certificate);
12733
        ssl->buffers.weOwnCert = 0;
12734
    }
12735
    ssl->buffers.certificate = NULL;
12736
    if (ssl->buffers.weOwnCertChain) {
12737
        FreeDer(&ssl->buffers.certChain);
12738
        ssl->buffers.weOwnCertChain = 0;
12739
    }
12740
    ssl->buffers.certChain = NULL;
12741
#ifdef WOLFSSL_TLS13
12742
    ssl->buffers.certChainCnt = 0;
12743
#endif
12744
    if (ssl->buffers.weOwnKey) {
12745
        FreeDer(&ssl->buffers.key);
12746
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12747
        FreeDer(&ssl->buffers.keyMask);
12748
    #endif
12749
        ssl->buffers.weOwnKey = 0;
12750
    }
12751
    ssl->buffers.key      = NULL;
12752
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12753
    ssl->buffers.keyMask  = NULL;
12754
#endif
12755
    ssl->buffers.keyType  = 0;
12756
    ssl->buffers.keyId    = 0;
12757
    ssl->buffers.keyLabel = 0;
12758
    ssl->buffers.keySz    = 0;
12759
    ssl->buffers.keyDevId = 0;
12760
#ifdef WOLFSSL_DUAL_ALG_CERTS
12761
    if (ssl->buffers.weOwnAltKey) {
12762
        FreeDer(&ssl->buffers.altKey);
12763
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12764
        FreeDer(&ssl->buffers.altKeyMask);
12765
    #endif
12766
        ssl->buffers.weOwnAltKey = 0;
12767
    }
12768
    ssl->buffers.altKey     = NULL;
12769
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12770
    ssl->buffers.altKeyMask = NULL;
12771
#endif
12772
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12773
}
12774
#endif
12775
12776
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
12777
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
12778
12779
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
12780
{
12781
    WOLFSSL_ENTER("wolfSSL_ctrl");
12782
    if (ssl == NULL)
12783
        return BAD_FUNC_ARG;
12784
12785
    switch (cmd) {
12786
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
12787
            defined(OPENSSL_ALL)
12788
        #ifdef HAVE_SNI
12789
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
12790
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
12791
            if (pt == NULL) {
12792
                WOLFSSL_MSG("Passed in NULL Host Name.");
12793
                break;
12794
            }
12795
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
12796
        #endif /* HAVE_SNI */
12797
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
12798
        default:
12799
            WOLFSSL_MSG("Case not implemented.");
12800
    }
12801
    (void)opt;
12802
    (void)pt;
12803
    return WOLFSSL_FAILURE;
12804
}
12805
12806
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
12807
{
12808
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
12809
    long ctrl_opt;
12810
#endif
12811
    long ret = WOLFSSL_SUCCESS;
12812
12813
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
12814
    if (ctx == NULL)
12815
        return WOLFSSL_FAILURE;
12816
12817
    switch (cmd) {
12818
    case SSL_CTRL_CHAIN:
12819
#ifdef SESSION_CERTS
12820
    {
12821
        /*
12822
         * We don't care about opt here because a copy of the certificate is
12823
         * stored anyway so increasing the reference counter is not necessary.
12824
         * Just check to make sure that it is set to one of the correct values.
12825
         */
12826
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
12827
        WOLFSSL_X509* x509;
12828
        int i;
12829
        if (opt != 0 && opt != 1) {
12830
            ret = WOLFSSL_FAILURE;
12831
            break;
12832
        }
12833
        /* Clear certificate chain */
12834
        FreeDer(&ctx->certChain);
12835
        if (sk) {
12836
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
12837
                x509 = wolfSSL_sk_X509_value(sk, i);
12838
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
12839
                if (wolfSSL_X509_up_ref(x509) != 1) {
12840
                    WOLFSSL_MSG("Error increasing reference count");
12841
                    continue;
12842
                }
12843
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
12844
                        WOLFSSL_SUCCESS) {
12845
                    WOLFSSL_MSG("Error adding certificate to context");
12846
                    /* Decrease reference count on failure */
12847
                    wolfSSL_X509_free(x509);
12848
                    x509 = NULL;
12849
                }
12850
            }
12851
        }
12852
        /* Free previous chain */
12853
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
12854
        ctx->x509Chain = sk;
12855
        if (sk && opt == 1) {
12856
            /* up all refs when opt == 1 */
12857
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
12858
                x509 = wolfSSL_sk_X509_value(sk, i);
12859
                if (wolfSSL_X509_up_ref(x509) != 1) {
12860
                    WOLFSSL_MSG("Error increasing reference count");
12861
                    continue;
12862
                }
12863
            }
12864
        }
12865
    }
12866
#else
12867
        WOLFSSL_MSG("Session certificates not compiled in");
12868
        ret = WOLFSSL_FAILURE;
12869
#endif
12870
        break;
12871
12872
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
12873
    case SSL_CTRL_OPTIONS:
12874
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
12875
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
12876
12877
        #ifdef WOLFSSL_QT
12878
        /* Set whether to use client or server cipher preference */
12879
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
12880
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
12881
            WOLFSSL_MSG("Using Server's Cipher Preference.");
12882
            ctx->useClientOrder = 0;
12883
        } else {
12884
            WOLFSSL_MSG("Using Client's Cipher Preference.");
12885
            ctx->useClientOrder = 1;
12886
        }
12887
        #endif /* WOLFSSL_QT */
12888
12889
        return ctrl_opt;
12890
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
12891
    case SSL_CTRL_EXTRA_CHAIN_CERT:
12892
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
12893
        if (pt == NULL) {
12894
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
12895
            ret = WOLFSSL_FAILURE;
12896
            break;
12897
        }
12898
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
12899
12900
#ifndef NO_DH
12901
    case SSL_CTRL_SET_TMP_DH:
12902
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
12903
        if (pt == NULL) {
12904
            WOLFSSL_MSG("Passed in DH pointer NULL.");
12905
            ret = WOLFSSL_FAILURE;
12906
            break;
12907
        }
12908
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
12909
#endif
12910
12911
#ifdef HAVE_ECC
12912
    case SSL_CTRL_SET_TMP_ECDH:
12913
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
12914
        if (pt == NULL) {
12915
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
12916
            ret = WOLFSSL_FAILURE;
12917
            break;
12918
        }
12919
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
12920
#endif
12921
    case SSL_CTRL_MODE:
12922
        wolfSSL_CTX_set_mode(ctx,opt);
12923
        break;
12924
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
12925
        WOLFSSL_MSG("set min proto version");
12926
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
12927
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
12928
        WOLFSSL_MSG("set max proto version");
12929
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
12930
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
12931
        WOLFSSL_MSG("get min proto version");
12932
        return wolfSSL_CTX_get_min_proto_version(ctx);
12933
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
12934
        WOLFSSL_MSG("get max proto version");
12935
        return wolfSSL_CTX_get_max_proto_version(ctx);
12936
    default:
12937
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
12938
        ret = WOLFSSL_FAILURE;
12939
        break;
12940
    }
12941
12942
    (void)ctx;
12943
    (void)cmd;
12944
    (void)opt;
12945
    (void)pt;
12946
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
12947
    return ret;
12948
}
12949
12950
#ifndef NO_WOLFSSL_STUB
12951
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
12952
{
12953
    (void) ctx;
12954
    (void) cmd;
12955
    (void) fp;
12956
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
12957
    return WOLFSSL_FAILURE;
12958
12959
}
12960
#endif /* NO_WOLFSSL_STUB */
12961
12962
12963
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
12964
12965
12966
/* stunnel compatibility functions*/
12967
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
12968
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
12969
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
12970
     defined(WOLFSSL_OPENSSH)))
12971
void wolfSSL_ERR_remove_thread_state(void* pid)
12972
{
12973
    (void) pid;
12974
    return;
12975
}
12976
12977
#ifndef NO_FILESYSTEM
12978
/***TBD ***/
12979
void wolfSSL_print_all_errors_fp(XFILE fp)
12980
{
12981
    (void)fp;
12982
}
12983
#endif /* !NO_FILESYSTEM */
12984
12985
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
12986
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
12987
12988
/* Note: This is a huge section of API's - through
12989
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
12990
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
12991
12992
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
12993
    !defined(WOLFSSL_STATIC_MEMORY)
12994
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
12995
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
12996
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
12997
12998
static void* OSSL_Malloc(size_t size)
12999
{
13000
    if (ossl_malloc != NULL)
13001
        return ossl_malloc(size, NULL, 0);
13002
    else
13003
        return NULL;
13004
}
13005
13006
static void  OSSL_Free(void *ptr)
13007
{
13008
    if (ossl_free != NULL)
13009
        ossl_free(ptr, NULL, 0);
13010
}
13011
13012
static void* OSSL_Realloc(void *ptr, size_t size)
13013
{
13014
    if (ossl_realloc != NULL)
13015
        return ossl_realloc(ptr, size, NULL, 0);
13016
    else
13017
        return NULL;
13018
}
13019
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
13020
        * !WOLFSSL_STATIC_MEMORY */
13021
13022
int wolfSSL_CRYPTO_set_mem_functions(
13023
        wolfSSL_OSSL_Malloc_cb  m,
13024
        wolfSSL_OSSL_Realloc_cb r,
13025
        wolfSSL_OSSL_Free_cb    f)
13026
{
13027
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
13028
#ifdef WOLFSSL_DEBUG_MEMORY
13029
    WOLFSSL_MSG("mem functions will receive function name instead of "
13030
                "file name");
13031
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
13032
            (wolfSSL_Realloc_cb)r) == 0)
13033
        return WOLFSSL_SUCCESS;
13034
#else
13035
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
13036
                "functions will receive a NULL file name and 0 for the "
13037
                "line number.");
13038
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
13039
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
13040
        ossl_malloc = m;
13041
        ossl_free = f;
13042
        ossl_realloc = r;
13043
        return WOLFSSL_SUCCESS;
13044
    }
13045
#endif
13046
    else
13047
        return WOLFSSL_FAILURE;
13048
#else
13049
    (void)m;
13050
    (void)r;
13051
    (void)f;
13052
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
13053
    return WOLFSSL_FAILURE;
13054
#endif
13055
}
13056
13057
int wolfSSL_ERR_load_ERR_strings(void)
13058
{
13059
    return WOLFSSL_SUCCESS;
13060
}
13061
13062
void wolfSSL_ERR_load_crypto_strings(void)
13063
{
13064
    WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings");
13065
    /* Do nothing */
13066
    return;
13067
}
13068
13069
int wolfSSL_FIPS_mode(void)
13070
{
13071
#ifdef HAVE_FIPS
13072
    return 1;
13073
#else
13074
    return 0;
13075
#endif
13076
}
13077
13078
int wolfSSL_FIPS_mode_set(int r)
13079
{
13080
#ifdef HAVE_FIPS
13081
    if (r == 0) {
13082
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
13083
        return WOLFSSL_FAILURE;
13084
    }
13085
    return WOLFSSL_SUCCESS;
13086
#else
13087
    if (r == 0) {
13088
        return WOLFSSL_SUCCESS;
13089
    }
13090
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
13091
    return WOLFSSL_FAILURE;
13092
#endif
13093
}
13094
13095
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
13096
{
13097
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
13098
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
13099
13100
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
13101
    (void)alg_bits;
13102
    if (c!= NULL)
13103
        ret = c->bits;
13104
    #else
13105
    if (c != NULL && c->ssl != NULL) {
13106
        ret = 8 * c->ssl->specs.key_size;
13107
        if (alg_bits != NULL) {
13108
            *alg_bits = ret;
13109
        }
13110
    }
13111
    #endif
13112
    return ret;
13113
}
13114
13115
13116
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
13117
{
13118
    int ret;
13119
    /* This method requires some explanation. Its sibling is
13120
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
13121
     * which re-inits the WOLFSSL* with all settings in the new CTX.
13122
     * That one is the right one to use *before* a handshake is started.
13123
     *
13124
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
13125
     * when a server inspects the SNI in a ClientHello callback and
13126
     * decides which set of certificates to use.
13127
     *
13128
     * Since, at the time the SNI callback is run, some decisions on
13129
     * Extensions or the ServerHello might already have been taken, this
13130
     * method is very restricted in what it does:
13131
     * - changing the server certificate(s)
13132
     * - changing the server id for session handling
13133
     * and everything else in WOLFSSL* needs to remain untouched.
13134
     *
13135
     * SECURITY: swapping ssl->ctx switches cm-resolved settings (CA store,
13136
     * CRL, OCSP) to the new CTX but leaves ssl-cached ones (verify mode and
13137
     * callback, minDowngrade, key-size minimums, suites, version bounds)
13138
     * pinned to the original. SNI callbacks must re-apply those ssl-level
13139
     * settings explicitly; CRL/OCSP isolation requires an SSL-local store.
13140
     */
13141
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
13142
    if (ssl == NULL || ctx == NULL)
13143
        return NULL;
13144
    if (ssl->ctx == ctx)
13145
        return ssl->ctx;
13146
13147
    if (ctx->suites == NULL) {
13148
        /* suites */
13149
        if (AllocateCtxSuites(ctx) != 0)
13150
            return NULL;
13151
        InitSSL_CTX_Suites(ctx);
13152
    }
13153
13154
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
13155
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
13156
    if (ret != 0) {
13157
        /* can only fail on serious stuff, like mutex not working
13158
         * or ctx refcount out of whack. */
13159
        return NULL;
13160
    }
13161
#else
13162
    (void)ret;
13163
#endif
13164
    if (ssl->ctx != NULL)
13165
        wolfSSL_CTX_free(ssl->ctx);
13166
    ssl->ctx = ctx;
13167
13168
#ifndef NO_CERTS
13169
#ifdef WOLFSSL_COPY_CERT
13170
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
13171
    if (ctx->certificate != NULL) {
13172
        if (ssl->buffers.certificate != NULL) {
13173
            FreeDer(&ssl->buffers.certificate);
13174
            ssl->buffers.certificate = NULL;
13175
        }
13176
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
13177
            ctx->certificate->length, ctx->certificate->type,
13178
            ctx->certificate->heap);
13179
        if (ret != 0) {
13180
            ssl->buffers.weOwnCert = 0;
13181
            return NULL;
13182
        }
13183
13184
        ssl->buffers.weOwnCert = 1;
13185
    }
13186
    if (ctx->certChain != NULL) {
13187
        if (ssl->buffers.certChain != NULL) {
13188
            FreeDer(&ssl->buffers.certChain);
13189
            ssl->buffers.certChain = NULL;
13190
        }
13191
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
13192
            ctx->certChain->length, ctx->certChain->type,
13193
            ctx->certChain->heap);
13194
        if (ret != 0) {
13195
            ssl->buffers.weOwnCertChain = 0;
13196
            return NULL;
13197
        }
13198
13199
        ssl->buffers.weOwnCertChain = 1;
13200
    }
13201
#else
13202
    /* ctx owns certificate, certChain and key */
13203
    ssl->buffers.certificate = ctx->certificate;
13204
    ssl->buffers.certChain = ctx->certChain;
13205
#endif
13206
#ifdef WOLFSSL_TLS13
13207
    ssl->buffers.certChainCnt = ctx->certChainCnt;
13208
#endif
13209
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
13210
#ifdef WOLFSSL_COPY_KEY
13211
    if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
13212
        FreeDer(&ssl->buffers.key);
13213
    }
13214
    if (ctx->privateKey != NULL) {
13215
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
13216
            ctx->privateKey->length, ctx->privateKey->type,
13217
            ctx->privateKey->heap);
13218
        if (ret != 0) {
13219
            ssl->buffers.weOwnKey = 0;
13220
            return NULL;
13221
        }
13222
        ssl->buffers.weOwnKey = 1;
13223
    }
13224
    else {
13225
        ssl->buffers.key      = ctx->privateKey;
13226
    }
13227
#else
13228
    ssl->buffers.key      = ctx->privateKey;
13229
#endif
13230
#else
13231
    if (ctx->privateKey != NULL) {
13232
        if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
13233
            FreeDer(&ssl->buffers.key);
13234
        }
13235
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
13236
            ctx->privateKey->length, ctx->privateKey->type,
13237
            ctx->privateKey->heap);
13238
        if (ret != 0) {
13239
            return NULL;
13240
        }
13241
        /* Blind the private key for the SSL with new random mask. */
13242
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
13243
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
13244
            &ssl->buffers.keyMask);
13245
        if (ret != 0) {
13246
            return NULL;
13247
        }
13248
    }
13249
#endif
13250
    ssl->buffers.keyType  = ctx->privateKeyType;
13251
    ssl->buffers.keyId    = ctx->privateKeyId;
13252
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
13253
    ssl->buffers.keySz    = ctx->privateKeySz;
13254
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
13255
    /* flags indicating what certs/keys are available */
13256
    ssl->options.haveRSA          = ctx->haveRSA;
13257
    ssl->options.haveDH           = ctx->haveDH;
13258
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
13259
    ssl->options.haveECC          = ctx->haveECC;
13260
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
13261
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
13262
    ssl->options.haveMlDsaSig = ctx->haveMlDsaSig;
13263
#ifdef WOLFSSL_DUAL_ALG_CERTS
13264
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
13265
    ssl->buffers.altKey   = ctx->altPrivateKey;
13266
#else
13267
    if (ctx->altPrivateKey != NULL) {
13268
        ret = AllocCopyDer(&ssl->buffers.altKey, ctx->altPrivateKey->buffer,
13269
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
13270
            ctx->altPrivateKey->heap);
13271
        if (ret != 0) {
13272
            return NULL;
13273
        }
13274
        /* Blind the private key for the SSL with new random mask. */
13275
        wolfssl_priv_der_blind_toggle(ssl->buffers.altKey,
13276
                                      ctx->altPrivateKeyMask);
13277
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
13278
            &ssl->buffers.altKeyMask);
13279
        if (ret != 0) {
13280
            return NULL;
13281
        }
13282
    }
13283
#endif
13284
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
13285
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
13286
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13287
#endif
13288
13289
#ifdef WOLFSSL_SESSION_ID_CTX
13290
    /* copy over application session context ID */
13291
    ssl->sessionCtxSz = ctx->sessionCtxSz;
13292
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
13293
#endif
13294
13295
    return ssl->ctx;
13296
}
13297
13298
13299
#ifndef NO_BIO
13300
void wolfSSL_ERR_load_BIO_strings(void) {
13301
    WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings");
13302
    /* do nothing */
13303
}
13304
#endif
13305
13306
#ifndef NO_WOLFSSL_STUB
13307
/* Set THREADID callback, return 1 on success, 0 on error */
13308
int wolfSSL_THREADID_set_callback(
13309
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
13310
{
13311
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
13312
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
13313
    (void)threadid_func;
13314
    return 1;
13315
}
13316
#endif
13317
13318
#ifndef NO_WOLFSSL_STUB
13319
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
13320
{
13321
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
13322
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
13323
    (void)id;
13324
    (void)val;
13325
    return;
13326
}
13327
#endif
13328
13329
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
13330
13331
13332
#if defined(OPENSSL_EXTRA)
13333
13334
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
13335
{
13336
    int ret = 0;
13337
    int chunk;
13338
    const byte* pa = (const byte*)a;
13339
    const byte* pb = (const byte*)b;
13340
13341
    if (!a || !b)
13342
        return -1;
13343
    /* ConstantCompare takes an int length. Compare in chunks of at most
13344
     * INT_MAX so a size that does not fit in an int is not narrowed into a
13345
     * negative or truncated length, which could wrongly report equality. */
13346
    while (size > 0) {
13347
        chunk = (size > (size_t)INT_MAX) ? INT_MAX : (int)size;
13348
        ret |= ConstantCompare(pa, pb, chunk);
13349
        pa += chunk;
13350
        pb += chunk;
13351
        size -= (size_t)chunk;
13352
    }
13353
    return ret;
13354
}
13355
13356
unsigned long wolfSSL_ERR_peek_last_error(void)
13357
{
13358
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
13359
13360
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
13361
    {
13362
        int ret;
13363
13364
        if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) {
13365
            WOLFSSL_MSG("Issue peeking at error node in queue");
13366
            return 0;
13367
        }
13368
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
13369
            return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
13370
    #if defined(WOLFSSL_PYTHON)
13371
        if (ret == ASN1_R_HEADER_TOO_LONG)
13372
            return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
13373
    #endif
13374
        return (unsigned long)ret;
13375
    }
13376
#else
13377
    return (unsigned long)(0 - NOT_COMPILED_IN);
13378
#endif
13379
}
13380
13381
#endif /* OPENSSL_EXTRA */
13382
13383
int wolfSSL_version(WOLFSSL* ssl)
13384
0
{
13385
0
    WOLFSSL_ENTER("wolfSSL_version");
13386
0
    if (ssl->version.major == SSLv3_MAJOR) {
13387
0
        switch (ssl->version.minor) {
13388
0
            case SSLv3_MINOR :
13389
0
                return SSL3_VERSION;
13390
0
            case TLSv1_MINOR :
13391
0
                return TLS1_VERSION;
13392
0
            case TLSv1_1_MINOR :
13393
0
                return TLS1_1_VERSION;
13394
0
            case TLSv1_2_MINOR :
13395
0
                return TLS1_2_VERSION;
13396
0
            case TLSv1_3_MINOR :
13397
0
                return TLS1_3_VERSION;
13398
0
            default:
13399
0
                return WOLFSSL_FAILURE;
13400
0
        }
13401
0
    }
13402
0
    else if (ssl->version.major == DTLS_MAJOR) {
13403
0
        switch (ssl->version.minor) {
13404
0
            case DTLS_MINOR :
13405
0
                return DTLS1_VERSION;
13406
0
            case DTLSv1_2_MINOR :
13407
0
                return DTLS1_2_VERSION;
13408
0
            case DTLSv1_3_MINOR:
13409
0
                return DTLS1_3_VERSION;
13410
0
            default:
13411
0
                return WOLFSSL_FAILURE;
13412
0
        }
13413
0
    }
13414
0
    return WOLFSSL_FAILURE;
13415
0
}
13416
13417
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
13418
0
{
13419
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
13420
0
    return ssl->ctx;
13421
0
}
13422
13423
13424
#ifdef WOLFSSL_JNI
13425
13426
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
13427
{
13428
    WOLFSSL_ENTER("wolfSSL_set_jobject");
13429
    if (ssl != NULL)
13430
    {
13431
        ssl->jObjectRef = objPtr;
13432
        return WOLFSSL_SUCCESS;
13433
    }
13434
    return WOLFSSL_FAILURE;
13435
}
13436
13437
void* wolfSSL_get_jobject(WOLFSSL* ssl)
13438
{
13439
    WOLFSSL_ENTER("wolfSSL_get_jobject");
13440
    if (ssl != NULL)
13441
        return ssl->jObjectRef;
13442
    return NULL;
13443
}
13444
13445
#endif /* WOLFSSL_JNI */
13446
13447
13448
#ifdef WOLFSSL_ASYNC_CRYPT
13449
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
13450
    WOLF_EVENT_FLAG flags, int* eventCount)
13451
{
13452
    if (ctx == NULL) {
13453
        return BAD_FUNC_ARG;
13454
    }
13455
13456
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
13457
                                        events, maxEvents, flags, eventCount);
13458
}
13459
13460
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
13461
{
13462
    int ret, eventCount = 0;
13463
    WOLF_EVENT* events[1];
13464
13465
    if (ssl == NULL) {
13466
        return BAD_FUNC_ARG;
13467
    }
13468
13469
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
13470
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
13471
    if (ret == 0) {
13472
        ret = eventCount;
13473
    }
13474
13475
    return ret;
13476
}
13477
#endif /* WOLFSSL_ASYNC_CRYPT */
13478
13479
#ifdef OPENSSL_EXTRA
13480
13481
static int peek_ignore_err(int err)
13482
{
13483
  switch(err) {
13484
    case -WC_NO_ERR_TRACE(WANT_READ):
13485
    case -WC_NO_ERR_TRACE(WANT_WRITE):
13486
    case -WC_NO_ERR_TRACE(ZERO_RETURN):
13487
    case -WOLFSSL_ERROR_ZERO_RETURN:
13488
    case -WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E):
13489
    case -WC_NO_ERR_TRACE(SOCKET_ERROR_E):
13490
      return 1;
13491
    default:
13492
      return 0;
13493
  }
13494
}
13495
13496
unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line,
13497
                                               const char **data, int *flags)
13498
{
13499
  unsigned long err;
13500
13501
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data");
13502
    err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err);
13503
13504
    if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
13505
        return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
13506
#ifdef OPENSSL_ALL
13507
    /* PARSE_ERROR is returned if an HTTP request is detected. */
13508
    else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR))
13509
        return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */;
13510
#endif
13511
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
13512
    else if (err == ASN1_R_HEADER_TOO_LONG)
13513
        return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
13514
#endif
13515
  return err;
13516
}
13517
#endif
13518
13519
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
13520
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
13521
13522
#if !defined(WOLFSSL_USER_IO)
13523
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
13524
 * example input would be "127.0.0.1" and the returned value would be 7F000001
13525
 */
13526
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
13527
{
13528
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
13529
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
13530
    int  af = WOLFSSL_IP4;
13531
    WOLFSSL_ASN1_STRING *ret = NULL;
13532
13533
    if (ipa == NULL)
13534
        return NULL;
13535
13536
    if (XSTRSTR(ipa, ":") != NULL) {
13537
        af = WOLFSSL_IP6;
13538
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
13539
    }
13540
13541
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
13542
#ifdef FREESCALE_MQX
13543
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
13544
#else
13545
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
13546
#endif
13547
        WOLFSSL_MSG("Error parsing IP address");
13548
        return NULL;
13549
    }
13550
13551
    ret = wolfSSL_ASN1_STRING_new();
13552
    if (ret != NULL) {
13553
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
13554
            WOLFSSL_MSG("Error setting the string");
13555
            wolfSSL_ASN1_STRING_free(ret);
13556
            ret = NULL;
13557
        }
13558
    }
13559
13560
    return ret;
13561
}
13562
#endif /* !WOLFSSL_USER_IO */
13563
13564
/* Is the specified cipher suite a fake one used an an extension proxy? */
13565
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
13566
{
13567
    (void)suite0;
13568
    (void)suite;
13569
#ifdef HAVE_RENEGOTIATION_INDICATION
13570
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
13571
        return 1;
13572
#endif
13573
    return 0;
13574
}
13575
13576
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
13577
        byte suite)
13578
{
13579
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13580
    int cipherSz = GetCipherNamesSize();
13581
    int i;
13582
    for (i = 0; i < cipherSz; i++)
13583
        if (cipher_names[i].cipherSuite0 == suite0 &&
13584
                cipher_names[i].cipherSuite == suite)
13585
            break;
13586
    if (i == cipherSz)
13587
        return 1;
13588
    /* Check min version */
13589
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
13590
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
13591
                cipher_names[i].minor >= TLSv1_MINOR)
13592
            /* 1.0 ciphersuites are in general available in 1.1 and
13593
             * 1.1 ciphersuites are in general available in 1.2 */
13594
            return 0;
13595
        return 1;
13596
    }
13597
    /* Check max version */
13598
    switch (cipher_names[i].minor) {
13599
    case SSLv3_MINOR :
13600
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
13601
    case TLSv1_MINOR :
13602
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
13603
    case TLSv1_1_MINOR :
13604
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
13605
    case TLSv1_2_MINOR :
13606
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
13607
    case TLSv1_3_MINOR :
13608
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
13609
    default:
13610
        WOLFSSL_MSG("Unrecognized minor version");
13611
        return 1;
13612
    }
13613
}
13614
13615
/* returns a pointer to internal cipher suite list. Should not be free'd by
13616
 * caller.
13617
 */
13618
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
13619
{
13620
    const Suites* suites;
13621
#if defined(OPENSSL_ALL)
13622
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13623
    int cipherSz = GetCipherNamesSize();
13624
#endif
13625
13626
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
13627
    if (ssl == NULL)
13628
        return NULL;
13629
13630
    suites = WOLFSSL_SUITES(ssl);
13631
    if (suites == NULL)
13632
        return NULL;
13633
13634
    /* check if stack needs populated */
13635
    if (ssl->suitesStack == NULL) {
13636
        int i;
13637
13638
        ((WOLFSSL*)ssl)->suitesStack =
13639
                wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, ssl->heap);
13640
        if (ssl->suitesStack == NULL)
13641
            return NULL;
13642
13643
        /* higher priority of cipher suite will be on top of stack */
13644
#if defined(OPENSSL_ALL)
13645
        for (i = suites->suiteSz - 2; i >=0; i-=2)
13646
#else
13647
        for (i = 0; i < suites->suiteSz; i+=2)
13648
#endif
13649
        {
13650
            struct WOLFSSL_CIPHER cipher;
13651
13652
            /* A couple of suites are placeholders for special options,
13653
             * skip those. */
13654
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
13655
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
13656
                                            suites->suites[i+1])) {
13657
                continue;
13658
            }
13659
13660
            XMEMSET(&cipher, 0, sizeof(cipher));
13661
            cipher.cipherSuite0 = suites->suites[i];
13662
            cipher.cipherSuite  = suites->suites[i+1];
13663
            cipher.ssl          = ssl;
13664
#if defined(OPENSSL_ALL)
13665
            cipher.in_stack     = 1;
13666
            {
13667
                int j;
13668
                for (j = 0; j < cipherSz; j++) {
13669
                    if (cipher_names[j].cipherSuite0 == cipher.cipherSuite0 &&
13670
                            cipher_names[j].cipherSuite == cipher.cipherSuite) {
13671
                        cipher.offset = (unsigned long)j;
13672
                        break;
13673
                    }
13674
                }
13675
            }
13676
#endif
13677
            if (wolfSSL_sk_insert(ssl->suitesStack, &cipher, 0) <= 0) {
13678
                WOLFSSL_MSG("Error inserting cipher onto stack");
13679
                wolfSSL_sk_CIPHER_free(ssl->suitesStack);
13680
                ((WOLFSSL*)ssl)->suitesStack = NULL;
13681
                break;
13682
            }
13683
        }
13684
13685
        /* If no ciphers were added, free empty stack and return NULL */
13686
        if (ssl->suitesStack != NULL && wolfSSL_sk_num(ssl->suitesStack) == 0) {
13687
            wolfSSL_sk_CIPHER_free(ssl->suitesStack);
13688
            ((WOLFSSL*)ssl)->suitesStack = NULL;
13689
        }
13690
    }
13691
    return ssl->suitesStack;
13692
}
13693
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
13694
#ifdef OPENSSL_ALL
13695
/* returned pointer is to an internal element in WOLFSSL struct and should not
13696
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
13697
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
13698
{
13699
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
13700
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13701
    int cipherSz = GetCipherNamesSize();
13702
    const Suites* suites;
13703
13704
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
13705
13706
    if (ssl == NULL) {
13707
        return NULL;
13708
    }
13709
13710
    /* return NULL if is client side */
13711
    if (wolfSSL_is_server(ssl) == 0) {
13712
        return NULL;
13713
    }
13714
13715
    suites = ssl->clSuites;
13716
    if (suites == NULL) {
13717
        WOLFSSL_MSG("No client suites stored");
13718
    }
13719
    else if (ssl->clSuitesStack != NULL) {
13720
        ret = ssl->clSuitesStack;
13721
    }
13722
    else { /* generate cipher suites stack if not already done */
13723
        int i;
13724
        int j;
13725
13726
        ret = wolfSSL_sk_new_node(ssl->heap);
13727
        if (ret != NULL) {
13728
            ret->type = STACK_TYPE_CIPHER;
13729
13730
            /* higher priority of cipher suite will be on top of stack */
13731
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
13732
                WOLFSSL_CIPHER cipher;
13733
13734
                /* A couple of suites are placeholders for special options,
13735
                 * skip those. */
13736
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
13737
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
13738
                                                suites->suites[i+1])) {
13739
                    continue;
13740
                }
13741
13742
                cipher.cipherSuite0 = suites->suites[i];
13743
                cipher.cipherSuite  = suites->suites[i+1];
13744
                cipher.ssl          = ssl;
13745
                for (j = 0; j < cipherSz; j++) {
13746
                    if (cipher_names[j].cipherSuite0 ==
13747
                            cipher.cipherSuite0 &&
13748
                            cipher_names[j].cipherSuite ==
13749
                                    cipher.cipherSuite) {
13750
                        cipher.offset = (unsigned long)j;
13751
                        break;
13752
                    }
13753
                }
13754
13755
                /* in_stack is checked in wolfSSL_CIPHER_description */
13756
                cipher.in_stack     = 1;
13757
13758
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
13759
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
13760
                    wolfSSL_sk_CIPHER_free(ret);
13761
                    ret = NULL;
13762
                    break;
13763
                }
13764
            }
13765
        }
13766
        ssl->clSuitesStack = ret;
13767
    }
13768
    return ret;
13769
}
13770
#endif /* OPENSSL_ALL */
13771
13772
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
13773
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
13774
{
13775
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
13776
13777
    if (ctx == NULL)
13778
        return 0;
13779
13780
    return ctx->timeout;
13781
}
13782
13783
13784
/* returns the time in seconds of the current timeout */
13785
long wolfSSL_get_timeout(WOLFSSL* ssl)
13786
{
13787
    WOLFSSL_ENTER("wolfSSL_get_timeout");
13788
13789
    if (ssl == NULL)
13790
        return 0;
13791
    return ssl->timeout;
13792
}
13793
#endif
13794
13795
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
13796
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
13797
13798
#ifndef NO_BIO
13799
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
13800
{
13801
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
13802
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
13803
     * The setting buffer size doesn't do anything so return NULL for both.
13804
     */
13805
    if (s == NULL)
13806
        return NULL;
13807
13808
    return s->biord;
13809
}
13810
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
13811
{
13812
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
13813
    (void)s;
13814
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
13815
     * The setting buffer size doesn't do anything so return NULL for both.
13816
     */
13817
    if (s == NULL)
13818
        return NULL;
13819
13820
    return s->biowr;
13821
}
13822
#endif /* !NO_BIO */
13823
13824
#ifndef NO_TLS
13825
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
13826
{
13827
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
13828
    if (s == NULL)
13829
        return WOLFSSL_FAILURE;
13830
13831
    if (s->options.side == WOLFSSL_CLIENT_END) {
13832
    #ifndef NO_WOLFSSL_CLIENT
13833
        return wolfSSL_connect(s);
13834
    #else
13835
        WOLFSSL_MSG("Client not compiled in");
13836
        return WOLFSSL_FAILURE;
13837
    #endif
13838
    }
13839
13840
#ifndef NO_WOLFSSL_SERVER
13841
    return wolfSSL_accept(s);
13842
#else
13843
    WOLFSSL_MSG("Server not compiled in");
13844
    return WOLFSSL_FAILURE;
13845
#endif
13846
}
13847
13848
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
13849
{
13850
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
13851
#ifdef WOLFSSL_QUIC
13852
    if (WOLFSSL_IS_QUIC(s)) {
13853
        return wolfSSL_quic_do_handshake(s);
13854
    }
13855
#endif
13856
    return wolfSSL_SSL_do_handshake_internal(s);
13857
}
13858
#endif /* !NO_TLS */
13859
13860
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
13861
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
13862
#else
13863
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
13864
#endif
13865
{
13866
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
13867
13868
    return !wolfSSL_is_init_finished(ssl);
13869
}
13870
13871
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
13872
{
13873
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
13874
13875
    if (ssl == NULL)
13876
        return WOLFSSL_FAILURE;
13877
13878
    return ssl->options.handShakeState == NULL_STATE;
13879
}
13880
13881
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
13882
{
13883
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
13884
13885
    if (ssl == NULL)
13886
        return WOLFSSL_FAILURE;
13887
13888
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
13889
        return ssl->options.connectState > CONNECT_BEGIN &&
13890
            ssl->options.connectState < SECOND_REPLY_DONE;
13891
    }
13892
13893
    return ssl->options.acceptState > ACCEPT_BEGIN &&
13894
        ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
13895
}
13896
13897
13898
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
13899
    OPENSSL_EXTRA || HAVE_LIGHTY */
13900
13901
13902
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
13903
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
13904
13905
13906
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
13907
{
13908
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
13909
13910
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
13911
}
13912
13913
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
13914
13915
13916
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
13917
13918
#if (defined(HAVE_ECC) || \
13919
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
13920
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
13921
13922
const WOLF_EC_NIST_NAME kNistCurves[] = {
13923
#ifdef HAVE_ECC
13924
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
13925
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
13926
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
13927
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
13928
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
13929
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
13930
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
13931
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
13932
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
13933
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
13934
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
13935
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
13936
     WOLFSSL_ECC_BRAINPOOLP256R1},
13937
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
13938
     WOLFSSL_ECC_BRAINPOOLP384R1},
13939
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
13940
     WOLFSSL_ECC_BRAINPOOLP512R1},
13941
#endif
13942
#ifdef HAVE_CURVE25519
13943
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
13944
#endif
13945
#ifdef HAVE_CURVE448
13946
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
13947
#endif
13948
#ifdef WOLFSSL_HAVE_MLKEM
13949
#ifndef WOLFSSL_NO_ML_KEM
13950
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
13951
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
13952
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
13953
    /* Aliases accepting the OpenSSL/IANA spelling without underscores. */
13954
    {CURVE_NAME("MLKEM512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
13955
    {CURVE_NAME("MLKEM768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
13956
    {CURVE_NAME("MLKEM1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
13957
#if defined(HAVE_ECC)
13958
    #ifdef WOLFSSL_PQC_HYBRIDS
13959
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
13960
     WOLFSSL_SECP256R1MLKEM768},
13961
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
13962
     WOLFSSL_SECP384R1MLKEM1024},
13963
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
13964
     WOLFSSL_X25519MLKEM768},
13965
    #endif /* WOLFSSL_PQC_HYBRIDS */
13966
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
13967
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
13968
     WOLFSSL_SECP256R1MLKEM512},
13969
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
13970
     WOLFSSL_SECP384R1MLKEM768},
13971
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
13972
     WOLFSSL_SECP521R1MLKEM1024},
13973
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
13974
     WOLFSSL_X25519MLKEM512},
13975
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
13976
     WOLFSSL_X448MLKEM768},
13977
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
13978
#endif
13979
#endif /* !WOLFSSL_NO_ML_KEM */
13980
#ifdef WOLFSSL_MLKEM_KYBER
13981
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
13982
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
13983
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
13984
#if defined(HAVE_ECC)
13985
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
13986
     WOLFSSL_P256_KYBER_LEVEL1},
13987
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
13988
     WOLFSSL_P384_KYBER_LEVEL3},
13989
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
13990
     WOLFSSL_P256_KYBER_LEVEL3},
13991
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
13992
     WOLFSSL_P521_KYBER_LEVEL5},
13993
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
13994
     WOLFSSL_X25519_KYBER_LEVEL1},
13995
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
13996
     WOLFSSL_X448_KYBER_LEVEL3},
13997
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
13998
     WOLFSSL_X25519_KYBER_LEVEL3},
13999
#endif
14000
#endif /* WOLFSSL_MLKEM_KYBER */
14001
#endif /* WOLFSSL_HAVE_MLKEM */
14002
#ifdef WOLFSSL_SM2
14003
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
14004
#endif
14005
#ifdef HAVE_ECC
14006
    /* Alternative curve names */
14007
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
14008
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
14009
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
14010
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
14011
#endif
14012
#ifdef WOLFSSL_SM2
14013
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
14014
#endif
14015
    {0, NULL, 0, 0},
14016
};
14017
14018
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
14019
        byte curves_only)
14020
{
14021
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
14022
    word16 curve;
14023
    word32 disabled;
14024
    char name[MAX_CURVE_NAME_SZ];
14025
    byte groups_len = 0;
14026
#ifdef WOLFSSL_SMALL_STACK
14027
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
14028
    int *groups;
14029
#else
14030
    int groups[WOLFSSL_MAX_GROUP_COUNT];
14031
#endif
14032
    const WOLF_EC_NIST_NAME* nist_name;
14033
14034
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
14035
        DYNAMIC_TYPE_TMP_BUFFER,
14036
    {
14037
        ret=MEMORY_E;
14038
        goto leave;
14039
    });
14040
14041
    for (idx = 1; names[idx-1] != '\0'; idx++) {
14042
        if (names[idx] != ':' && names[idx] != '\0')
14043
            continue;
14044
14045
        len = idx - start;
14046
        if (len > MAX_CURVE_NAME_SZ - 1)
14047
            goto leave;
14048
14049
        XMEMCPY(name, names + start, (size_t)len);
14050
        name[len] = 0;
14051
        curve = WOLFSSL_NAMED_GROUP_INVALID;
14052
14053
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
14054
            if (len == nist_name->name_len &&
14055
                    XSTRNCASECMP(name, nist_name->name, (size_t)len) == 0) {
14056
                curve = nist_name->curve;
14057
                break;
14058
            }
14059
        }
14060
14061
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
14062
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
14063
            int   nret;
14064
            const ecc_set_type *eccSet;
14065
14066
            nret = wc_ecc_get_curve_idx_from_name(name);
14067
            if (nret < 0) {
14068
                WOLFSSL_MSG("Could not find name in set");
14069
                goto leave;
14070
            }
14071
14072
            eccSet = wc_ecc_get_curve_params(nret);
14073
            if (eccSet == NULL) {
14074
                WOLFSSL_MSG("NULL set returned");
14075
                goto leave;
14076
            }
14077
14078
            curve = GetCurveByOID((int)eccSet->oidSum);
14079
        #else
14080
            WOLFSSL_MSG("API not present to search farther using name");
14081
            goto leave;
14082
        #endif
14083
        }
14084
14085
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
14086
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
14087
            WOLFSSL_MSG("curve value is not supported");
14088
            goto leave;
14089
        }
14090
14091
        for (i = 0; i < groups_len; ++i) {
14092
            if (groups[i] == curve) {
14093
                /* silently drop duplicates */
14094
                break;
14095
            }
14096
        }
14097
        if (i >= groups_len) {
14098
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
14099
                WOLFSSL_MSG_EX("setting %d or more supported "
14100
                               "curves is not permitted", groups_len);
14101
                goto leave;
14102
            }
14103
            groups[groups_len++] = (int)curve;
14104
        }
14105
14106
        start = idx + 1;
14107
    }
14108
14109
    /* Disable all curves so that only the ones the user wants are enabled. */
14110
    disabled = 0xFFFFFFFFUL;
14111
    for (i = 0; i < groups_len; ++i) {
14112
        /* Switch the bit to off and therefore is enabled. */
14113
        curve = (word16)groups[i];
14114
        if (curve >= 64) {
14115
            WC_DO_NOTHING;
14116
        }
14117
        else if (curve >= 32) {
14118
            /* 0 is for invalid and 1-14 aren't used otherwise. */
14119
            disabled &= ~(1U << (curve - 32));
14120
        }
14121
        else {
14122
            disabled &= ~(1U << curve);
14123
        }
14124
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
14125
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
14126
        /* using the wolfSSL API to set the groups, this will populate
14127
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
14128
         * The order in (ssl|ctx)->groups will then be respected
14129
         * when TLSX_KEY_SHARE needs to be established */
14130
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
14131
                        != WOLFSSL_SUCCESS)
14132
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
14133
                           != WOLFSSL_SUCCESS)) {
14134
            WOLFSSL_MSG("Unable to set supported curve");
14135
            goto leave;
14136
        }
14137
    #elif !defined(NO_WOLFSSL_CLIENT)
14138
        /* set the supported curve so client TLS extension contains only the
14139
         * desired curves */
14140
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
14141
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
14142
                           != WOLFSSL_SUCCESS)) {
14143
            WOLFSSL_MSG("Unable to set supported curve");
14144
            goto leave;
14145
        }
14146
    #endif
14147
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
14148
    }
14149
14150
    if (ssl != NULL)
14151
        ssl->disabledCurves = disabled;
14152
    else if (ctx != NULL)
14153
        ctx->disabledCurves = disabled;
14154
    ret = WOLFSSL_SUCCESS;
14155
14156
leave:
14157
#ifdef WOLFSSL_SMALL_STACK
14158
    if (groups)
14159
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
14160
#endif
14161
    return ret;
14162
}
14163
14164
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
14165
#endif /* OPENSSL_EXTRA || HAVE_CURL */
14166
14167
14168
#ifdef OPENSSL_EXTRA
14169
/* Sets a callback for when sending and receiving protocol messages.
14170
 * This callback is copied to all WOLFSSL objects created from the ctx.
14171
 *
14172
 * ctx WOLFSSL_CTX structure to set callback in
14173
 * cb  callback to use
14174
 *
14175
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
14176
 */
14177
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
14178
{
14179
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
14180
    if (ctx == NULL) {
14181
        WOLFSSL_MSG("Null ctx passed in");
14182
        return WOLFSSL_FAILURE;
14183
    }
14184
14185
    ctx->protoMsgCb = cb;
14186
    return WOLFSSL_SUCCESS;
14187
}
14188
14189
14190
/* Sets a callback for when sending and receiving protocol messages.
14191
 *
14192
 * ssl WOLFSSL structure to set callback in
14193
 * cb  callback to use
14194
 *
14195
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
14196
 */
14197
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
14198
{
14199
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
14200
14201
    if (ssl == NULL) {
14202
        return WOLFSSL_FAILURE;
14203
    }
14204
14205
    if (cb != NULL) {
14206
        ssl->toInfoOn = 1;
14207
    }
14208
14209
    ssl->protoMsgCb = cb;
14210
    return WOLFSSL_SUCCESS;
14211
}
14212
14213
14214
/* set the user argument to pass to the msg callback when called
14215
 * return WOLFSSL_SUCCESS on success */
14216
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
14217
{
14218
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
14219
    if (ctx == NULL) {
14220
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
14221
        return WOLFSSL_FAILURE;
14222
    }
14223
14224
    ctx->protoMsgCtx = arg;
14225
    return WOLFSSL_SUCCESS;
14226
}
14227
14228
14229
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
14230
{
14231
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
14232
    if (ssl == NULL)
14233
        return WOLFSSL_FAILURE;
14234
14235
    ssl->protoMsgCtx = arg;
14236
    return WOLFSSL_SUCCESS;
14237
}
14238
14239
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
14240
    int line)
14241
{
14242
    void *ret;
14243
    (void)file;
14244
    (void)line;
14245
14246
    if (data == NULL || siz >= INT_MAX)
14247
        return NULL;
14248
14249
    ret = wolfSSL_OPENSSL_malloc(siz);
14250
    if (ret == NULL) {
14251
        return NULL;
14252
    }
14253
    return XMEMCPY(ret, data, siz);
14254
}
14255
14256
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
14257
{
14258
    if (ptr)
14259
        ForceZero(ptr, (word32)len);
14260
}
14261
14262
#endif /* OPENSSL_EXTRA */
14263
14264
#define WOLFSSL_SSL_API_EXT_INCLUDED
14265
#include "src/ssl_api_ext.c"
14266
14267
#if defined(OPENSSL_EXTRA)
14268
14269
#ifndef NO_BIO
14270
#define WOLFSSL_BIO_INCLUDED
14271
#include "src/bio.c"
14272
#endif
14273
14274
#endif /* OPENSSL_EXTRA */
14275
14276
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
14277
14278
word32 nid2oid(int nid, int grp)
14279
{
14280
    /* get OID type */
14281
    switch (grp) {
14282
        /* oidHashType */
14283
        case oidHashType:
14284
            switch (nid) {
14285
            #ifdef WOLFSSL_MD2
14286
                case WC_NID_md2:
14287
                    return MD2h;
14288
            #endif
14289
            #ifndef NO_MD5
14290
                case WC_NID_md5:
14291
                    return MD5h;
14292
            #endif
14293
            #ifndef NO_SHA
14294
                case WC_NID_sha1:
14295
                    return SHAh;
14296
            #endif
14297
                case WC_NID_sha224:
14298
                    return SHA224h;
14299
            #ifndef NO_SHA256
14300
                case WC_NID_sha256:
14301
                    return SHA256h;
14302
            #endif
14303
            #ifdef WOLFSSL_SHA384
14304
                case WC_NID_sha384:
14305
                    return SHA384h;
14306
            #endif
14307
            #ifdef WOLFSSL_SHA512
14308
                case WC_NID_sha512:
14309
                    return SHA512h;
14310
            #endif
14311
            #ifndef WOLFSSL_NOSHA3_224
14312
                case WC_NID_sha3_224:
14313
                    return SHA3_224h;
14314
            #endif
14315
            #ifndef WOLFSSL_NOSHA3_256
14316
                case WC_NID_sha3_256:
14317
                    return SHA3_256h;
14318
            #endif
14319
            #ifndef WOLFSSL_NOSHA3_384
14320
                case WC_NID_sha3_384:
14321
                    return SHA3_384h;
14322
            #endif
14323
            #ifndef WOLFSSL_NOSHA3_512
14324
                case WC_NID_sha3_512:
14325
                    return SHA3_512h;
14326
            #endif
14327
            }
14328
            break;
14329
14330
        /*  oidSigType */
14331
        case oidSigType:
14332
            switch (nid) {
14333
            #ifndef NO_DSA
14334
                case WC_NID_dsaWithSHA1:
14335
                    return CTC_SHAwDSA;
14336
                case WC_NID_dsa_with_SHA256:
14337
                    return CTC_SHA256wDSA;
14338
            #endif /* NO_DSA */
14339
            #ifndef NO_RSA
14340
                case WC_NID_md2WithRSAEncryption:
14341
                    return CTC_MD2wRSA;
14342
                case WC_NID_md5WithRSAEncryption:
14343
                    return CTC_MD5wRSA;
14344
                case WC_NID_sha1WithRSAEncryption:
14345
                    return CTC_SHAwRSA;
14346
                case WC_NID_sha224WithRSAEncryption:
14347
                    return CTC_SHA224wRSA;
14348
                case WC_NID_sha256WithRSAEncryption:
14349
                    return CTC_SHA256wRSA;
14350
                case WC_NID_sha384WithRSAEncryption:
14351
                    return CTC_SHA384wRSA;
14352
                case WC_NID_sha512WithRSAEncryption:
14353
                    return CTC_SHA512wRSA;
14354
                #ifdef WOLFSSL_SHA3
14355
                case WC_NID_RSA_SHA3_224:
14356
                    return CTC_SHA3_224wRSA;
14357
                case WC_NID_RSA_SHA3_256:
14358
                    return CTC_SHA3_256wRSA;
14359
                case WC_NID_RSA_SHA3_384:
14360
                    return CTC_SHA3_384wRSA;
14361
                case WC_NID_RSA_SHA3_512:
14362
                    return CTC_SHA3_512wRSA;
14363
                #endif
14364
            #endif /* NO_RSA */
14365
            #ifdef HAVE_ECC
14366
                case WC_NID_ecdsa_with_SHA1:
14367
                    return CTC_SHAwECDSA;
14368
                case WC_NID_ecdsa_with_SHA224:
14369
                    return CTC_SHA224wECDSA;
14370
                case WC_NID_ecdsa_with_SHA256:
14371
                    return CTC_SHA256wECDSA;
14372
                case WC_NID_ecdsa_with_SHA384:
14373
                    return CTC_SHA384wECDSA;
14374
                case WC_NID_ecdsa_with_SHA512:
14375
                    return CTC_SHA512wECDSA;
14376
                #ifdef WOLFSSL_SHA3
14377
                case WC_NID_ecdsa_with_SHA3_224:
14378
                    return CTC_SHA3_224wECDSA;
14379
                case WC_NID_ecdsa_with_SHA3_256:
14380
                    return CTC_SHA3_256wECDSA;
14381
                case WC_NID_ecdsa_with_SHA3_384:
14382
                    return CTC_SHA3_384wECDSA;
14383
                case WC_NID_ecdsa_with_SHA3_512:
14384
                    return CTC_SHA3_512wECDSA;
14385
                #endif
14386
            #endif /* HAVE_ECC */
14387
            #ifdef HAVE_ED25519
14388
                case WC_NID_ED25519:
14389
                    return CTC_ED25519;
14390
            #endif /* HAVE_ED25519 */
14391
            #ifdef HAVE_ED448
14392
                case WC_NID_ED448:
14393
                    return CTC_ED448;
14394
            #endif /* HAVE_ED448 */
14395
            }
14396
            break;
14397
14398
        /* oidKeyType */
14399
        case oidKeyType:
14400
            switch (nid) {
14401
            #ifndef NO_DSA
14402
                case WC_NID_dsa:
14403
                    return DSAk;
14404
            #endif /* NO_DSA */
14405
            #ifndef NO_RSA
14406
                case WC_NID_rsaEncryption:
14407
                    return RSAk;
14408
            #endif /* NO_RSA */
14409
            #ifdef HAVE_ECC
14410
                case WC_NID_X9_62_id_ecPublicKey:
14411
                    return ECDSAk;
14412
            #endif /* HAVE_ECC */
14413
            #ifdef HAVE_ED25519
14414
                case WC_NID_ED25519:
14415
                    return ED25519k;
14416
            #endif /* HAVE_ED25519 */
14417
            #ifdef HAVE_ED448
14418
                case WC_NID_ED448:
14419
                    return ED448k;
14420
            #endif /* HAVE_ED448 */
14421
            }
14422
            break;
14423
14424
14425
    #ifdef HAVE_ECC
14426
        case oidCurveType:
14427
            switch (nid) {
14428
            case WC_NID_X9_62_prime192v1:
14429
                return ECC_SECP192R1_OID;
14430
            case WC_NID_X9_62_prime192v2:
14431
                return ECC_PRIME192V2_OID;
14432
            case WC_NID_X9_62_prime192v3:
14433
                return ECC_PRIME192V3_OID;
14434
            case WC_NID_X9_62_prime239v1:
14435
                return ECC_PRIME239V1_OID;
14436
            case WC_NID_X9_62_prime239v2:
14437
                return ECC_PRIME239V2_OID;
14438
            case WC_NID_X9_62_prime239v3:
14439
                return ECC_PRIME239V3_OID;
14440
            case WC_NID_X9_62_prime256v1:
14441
                return ECC_SECP256R1_OID;
14442
            case WC_NID_secp112r1:
14443
                return ECC_SECP112R1_OID;
14444
            case WC_NID_secp112r2:
14445
                return ECC_SECP112R2_OID;
14446
            case WC_NID_secp128r1:
14447
                return ECC_SECP128R1_OID;
14448
            case WC_NID_secp128r2:
14449
                return ECC_SECP128R2_OID;
14450
            case WC_NID_secp160r1:
14451
                return ECC_SECP160R1_OID;
14452
            case WC_NID_secp160r2:
14453
                return ECC_SECP160R2_OID;
14454
            case WC_NID_secp224r1:
14455
                return ECC_SECP224R1_OID;
14456
            case WC_NID_secp384r1:
14457
                return ECC_SECP384R1_OID;
14458
            case WC_NID_secp521r1:
14459
                return ECC_SECP521R1_OID;
14460
            case WC_NID_secp160k1:
14461
                return ECC_SECP160K1_OID;
14462
            case WC_NID_secp192k1:
14463
                return ECC_SECP192K1_OID;
14464
            case WC_NID_secp224k1:
14465
                return ECC_SECP224K1_OID;
14466
            case WC_NID_secp256k1:
14467
                return ECC_SECP256K1_OID;
14468
            case WC_NID_brainpoolP160r1:
14469
                return ECC_BRAINPOOLP160R1_OID;
14470
            case WC_NID_brainpoolP192r1:
14471
                return ECC_BRAINPOOLP192R1_OID;
14472
            case WC_NID_brainpoolP224r1:
14473
                return ECC_BRAINPOOLP224R1_OID;
14474
            case WC_NID_brainpoolP256r1:
14475
                return ECC_BRAINPOOLP256R1_OID;
14476
            case WC_NID_brainpoolP320r1:
14477
                return ECC_BRAINPOOLP320R1_OID;
14478
            case WC_NID_brainpoolP384r1:
14479
                return ECC_BRAINPOOLP384R1_OID;
14480
            case WC_NID_brainpoolP512r1:
14481
                return ECC_BRAINPOOLP512R1_OID;
14482
            }
14483
            break;
14484
    #endif /* HAVE_ECC */
14485
14486
        /* oidBlkType */
14487
        case oidBlkType:
14488
            switch (nid) {
14489
            #ifdef WOLFSSL_AES_128
14490
                case AES128CBCb:
14491
                    return AES128CBCb;
14492
            #endif
14493
            #ifdef WOLFSSL_AES_192
14494
                case AES192CBCb:
14495
                    return AES192CBCb;
14496
            #endif
14497
            #ifdef WOLFSSL_AES_256
14498
                case AES256CBCb:
14499
                    return AES256CBCb;
14500
            #endif
14501
            #ifndef NO_DES3
14502
                case WC_NID_des:
14503
                    return DESb;
14504
                case WC_NID_des3:
14505
                    return DES3b;
14506
            #endif
14507
            }
14508
            break;
14509
14510
    #ifdef HAVE_OCSP
14511
        case oidOcspType:
14512
            switch (nid) {
14513
                case WC_NID_id_pkix_OCSP_basic:
14514
                    return OCSP_BASIC_OID;
14515
                case OCSP_NONCE_OID:
14516
                    return OCSP_NONCE_OID;
14517
            }
14518
            break;
14519
    #endif /* HAVE_OCSP */
14520
14521
        /* oidCertExtType */
14522
        case oidCertExtType:
14523
            switch (nid) {
14524
                case WC_NID_basic_constraints:
14525
                    return BASIC_CA_OID;
14526
                case WC_NID_subject_alt_name:
14527
                    return ALT_NAMES_OID;
14528
                case WC_NID_crl_distribution_points:
14529
                    return CRL_DIST_OID;
14530
                case WC_NID_info_access:
14531
                    return AUTH_INFO_OID;
14532
                case WC_NID_authority_key_identifier:
14533
                    return AUTH_KEY_OID;
14534
                case WC_NID_subject_key_identifier:
14535
                    return SUBJ_KEY_OID;
14536
                case WC_NID_inhibit_any_policy:
14537
                    return INHIBIT_ANY_OID;
14538
                case WC_NID_key_usage:
14539
                    return KEY_USAGE_OID;
14540
                case WC_NID_name_constraints:
14541
                    return NAME_CONS_OID;
14542
                case WC_NID_certificate_policies:
14543
                    return CERT_POLICY_OID;
14544
                case WC_NID_ext_key_usage:
14545
                    return EXT_KEY_USAGE_OID;
14546
            }
14547
            break;
14548
14549
        /* oidCertAuthInfoType */
14550
        case oidCertAuthInfoType:
14551
            switch (nid) {
14552
                case WC_NID_ad_OCSP:
14553
                    return AIA_OCSP_OID;
14554
                case WC_NID_ad_ca_issuers:
14555
                    return AIA_CA_ISSUER_OID;
14556
            }
14557
            break;
14558
14559
        /* oidCertPolicyType */
14560
        case oidCertPolicyType:
14561
            switch (nid) {
14562
                case WC_NID_any_policy:
14563
                    return CP_ANY_OID;
14564
            }
14565
            break;
14566
14567
        /* oidCertAltNameType */
14568
        case oidCertAltNameType:
14569
            switch (nid) {
14570
                case WC_NID_hw_name_oid:
14571
                    return HW_NAME_OID;
14572
            }
14573
            break;
14574
14575
        /* oidCertKeyUseType */
14576
        case oidCertKeyUseType:
14577
            switch (nid) {
14578
                case WC_NID_anyExtendedKeyUsage:
14579
                    return EKU_ANY_OID;
14580
                case EKU_SERVER_AUTH_OID:
14581
                    return EKU_SERVER_AUTH_OID;
14582
                case EKU_CLIENT_AUTH_OID:
14583
                    return EKU_CLIENT_AUTH_OID;
14584
                case EKU_OCSP_SIGN_OID:
14585
                    return EKU_OCSP_SIGN_OID;
14586
            }
14587
            break;
14588
14589
        /* oidKdfType */
14590
        case oidKdfType:
14591
            switch (nid) {
14592
                case PBKDF2_OID:
14593
                    return PBKDF2_OID;
14594
            }
14595
            break;
14596
14597
        /* oidPBEType */
14598
        case oidPBEType:
14599
            switch (nid) {
14600
                case PBE_SHA1_RC4_128:
14601
                    return PBE_SHA1_RC4_128;
14602
                case PBE_SHA1_DES:
14603
                    return PBE_SHA1_DES;
14604
                case PBE_SHA1_DES3:
14605
                    return PBE_SHA1_DES3;
14606
            }
14607
            break;
14608
14609
        /* oidKeyWrapType */
14610
        case oidKeyWrapType:
14611
            switch (nid) {
14612
            #ifdef WOLFSSL_AES_128
14613
                case AES128_WRAP:
14614
                    return AES128_WRAP;
14615
            #endif
14616
            #ifdef WOLFSSL_AES_192
14617
                case AES192_WRAP:
14618
                    return AES192_WRAP;
14619
            #endif
14620
            #ifdef WOLFSSL_AES_256
14621
                case AES256_WRAP:
14622
                    return AES256_WRAP;
14623
            #endif
14624
            }
14625
            break;
14626
14627
        /* oidCmsKeyAgreeType */
14628
        case oidCmsKeyAgreeType:
14629
            switch (nid) {
14630
                #ifndef NO_SHA
14631
                case dhSinglePass_stdDH_sha1kdf_scheme:
14632
                    return dhSinglePass_stdDH_sha1kdf_scheme;
14633
                #endif
14634
                #ifdef WOLFSSL_SHA224
14635
                case dhSinglePass_stdDH_sha224kdf_scheme:
14636
                    return dhSinglePass_stdDH_sha224kdf_scheme;
14637
                #endif
14638
                #ifndef NO_SHA256
14639
                case dhSinglePass_stdDH_sha256kdf_scheme:
14640
                    return dhSinglePass_stdDH_sha256kdf_scheme;
14641
                #endif
14642
                #ifdef WOLFSSL_SHA384
14643
                case dhSinglePass_stdDH_sha384kdf_scheme:
14644
                    return dhSinglePass_stdDH_sha384kdf_scheme;
14645
                #endif
14646
                #ifdef WOLFSSL_SHA512
14647
                case dhSinglePass_stdDH_sha512kdf_scheme:
14648
                    return dhSinglePass_stdDH_sha512kdf_scheme;
14649
                #endif
14650
            }
14651
            break;
14652
14653
        /* oidCmsKeyAgreeType */
14654
    #ifdef WOLFSSL_CERT_REQ
14655
        case oidCsrAttrType:
14656
            switch (nid) {
14657
                case WC_NID_pkcs9_contentType:
14658
                    return PKCS9_CONTENT_TYPE_OID;
14659
                case WC_NID_pkcs9_challengePassword:
14660
                    return CHALLENGE_PASSWORD_OID;
14661
                case WC_NID_serialNumber:
14662
                    return SERIAL_NUMBER_OID;
14663
                case WC_NID_userId:
14664
                    return USER_ID_OID;
14665
                case WC_NID_surname:
14666
                    return SURNAME_OID;
14667
            }
14668
            break;
14669
    #endif
14670
14671
        default:
14672
            WOLFSSL_MSG("NID not in table");
14673
            /* MSVC warns without the cast */
14674
            return (word32)-1;
14675
    }
14676
14677
    /* MSVC warns without the cast */
14678
    return (word32)-1;
14679
}
14680
14681
int oid2nid(word32 oid, int grp)
14682
{
14683
    size_t i;
14684
    /* get OID type */
14685
    switch (grp) {
14686
        /* oidHashType */
14687
        case oidHashType:
14688
            switch (oid) {
14689
            #ifdef WOLFSSL_MD2
14690
                case MD2h:
14691
                    return WC_NID_md2;
14692
            #endif
14693
            #ifndef NO_MD5
14694
                case MD5h:
14695
                    return WC_NID_md5;
14696
            #endif
14697
            #ifndef NO_SHA
14698
                case SHAh:
14699
                    return WC_NID_sha1;
14700
            #endif
14701
                case SHA224h:
14702
                    return WC_NID_sha224;
14703
            #ifndef NO_SHA256
14704
                case SHA256h:
14705
                    return WC_NID_sha256;
14706
            #endif
14707
            #ifdef WOLFSSL_SHA384
14708
                case SHA384h:
14709
                    return WC_NID_sha384;
14710
            #endif
14711
            #ifdef WOLFSSL_SHA512
14712
                case SHA512h:
14713
                    return WC_NID_sha512;
14714
            #endif
14715
            }
14716
            break;
14717
14718
        /*  oidSigType */
14719
        case oidSigType:
14720
            switch (oid) {
14721
            #ifndef NO_DSA
14722
                case CTC_SHAwDSA:
14723
                    return WC_NID_dsaWithSHA1;
14724
                case CTC_SHA256wDSA:
14725
                    return WC_NID_dsa_with_SHA256;
14726
            #endif /* NO_DSA */
14727
            #ifndef NO_RSA
14728
                case CTC_MD2wRSA:
14729
                    return WC_NID_md2WithRSAEncryption;
14730
                case CTC_MD5wRSA:
14731
                    return WC_NID_md5WithRSAEncryption;
14732
                case CTC_SHAwRSA:
14733
                    return WC_NID_sha1WithRSAEncryption;
14734
                case CTC_SHA224wRSA:
14735
                    return WC_NID_sha224WithRSAEncryption;
14736
                case CTC_SHA256wRSA:
14737
                    return WC_NID_sha256WithRSAEncryption;
14738
                case CTC_SHA384wRSA:
14739
                    return WC_NID_sha384WithRSAEncryption;
14740
                case CTC_SHA512wRSA:
14741
                    return WC_NID_sha512WithRSAEncryption;
14742
                #ifdef WOLFSSL_SHA3
14743
                case CTC_SHA3_224wRSA:
14744
                    return WC_NID_RSA_SHA3_224;
14745
                case CTC_SHA3_256wRSA:
14746
                    return WC_NID_RSA_SHA3_256;
14747
                case CTC_SHA3_384wRSA:
14748
                    return WC_NID_RSA_SHA3_384;
14749
                case CTC_SHA3_512wRSA:
14750
                    return WC_NID_RSA_SHA3_512;
14751
                #endif
14752
                #ifdef WC_RSA_PSS
14753
                case CTC_RSASSAPSS:
14754
                    return WC_NID_rsassaPss;
14755
                #endif
14756
            #endif /* NO_RSA */
14757
            #ifdef HAVE_ECC
14758
                case CTC_SHAwECDSA:
14759
                    return WC_NID_ecdsa_with_SHA1;
14760
                case CTC_SHA224wECDSA:
14761
                    return WC_NID_ecdsa_with_SHA224;
14762
                case CTC_SHA256wECDSA:
14763
                    return WC_NID_ecdsa_with_SHA256;
14764
                case CTC_SHA384wECDSA:
14765
                    return WC_NID_ecdsa_with_SHA384;
14766
                case CTC_SHA512wECDSA:
14767
                    return WC_NID_ecdsa_with_SHA512;
14768
                #ifdef WOLFSSL_SHA3
14769
                case CTC_SHA3_224wECDSA:
14770
                    return WC_NID_ecdsa_with_SHA3_224;
14771
                case CTC_SHA3_256wECDSA:
14772
                    return WC_NID_ecdsa_with_SHA3_256;
14773
                case CTC_SHA3_384wECDSA:
14774
                    return WC_NID_ecdsa_with_SHA3_384;
14775
                case CTC_SHA3_512wECDSA:
14776
                    return WC_NID_ecdsa_with_SHA3_512;
14777
                #endif
14778
            #endif /* HAVE_ECC */
14779
            #ifdef HAVE_ED25519
14780
                case CTC_ED25519:
14781
                    return WC_NID_ED25519;
14782
            #endif /* HAVE_ED25519 */
14783
            #ifdef HAVE_ED448
14784
                case CTC_ED448:
14785
                    return WC_NID_ED448;
14786
            #endif /* HAVE_ED448 */
14787
            }
14788
            break;
14789
14790
        /* oidKeyType */
14791
        case oidKeyType:
14792
            switch (oid) {
14793
            #ifndef NO_DSA
14794
                case DSAk:
14795
                    return WC_NID_dsa;
14796
            #endif /* NO_DSA */
14797
            #ifndef NO_RSA
14798
                case RSAk:
14799
                    return WC_NID_rsaEncryption;
14800
                #ifdef WC_RSA_PSS
14801
                case RSAPSSk:
14802
                    return WC_NID_rsassaPss;
14803
                #endif
14804
            #endif /* NO_RSA */
14805
            #ifdef HAVE_ECC
14806
                case ECDSAk:
14807
                    return WC_NID_X9_62_id_ecPublicKey;
14808
            #endif /* HAVE_ECC */
14809
            #ifdef HAVE_ED25519
14810
                case ED25519k:
14811
                    return WC_NID_ED25519;
14812
            #endif /* HAVE_ED25519 */
14813
            #ifdef HAVE_ED448
14814
                case ED448k:
14815
                    return WC_NID_ED448;
14816
            #endif /* HAVE_ED448 */
14817
            }
14818
            break;
14819
14820
14821
    #ifdef HAVE_ECC
14822
        case oidCurveType:
14823
            switch (oid) {
14824
            case ECC_SECP192R1_OID:
14825
                return WC_NID_X9_62_prime192v1;
14826
            case ECC_PRIME192V2_OID:
14827
                return WC_NID_X9_62_prime192v2;
14828
            case ECC_PRIME192V3_OID:
14829
                return WC_NID_X9_62_prime192v3;
14830
            case ECC_PRIME239V1_OID:
14831
                return WC_NID_X9_62_prime239v1;
14832
            case ECC_PRIME239V2_OID:
14833
                return WC_NID_X9_62_prime239v2;
14834
            case ECC_PRIME239V3_OID:
14835
                return WC_NID_X9_62_prime239v3;
14836
            case ECC_SECP256R1_OID:
14837
                return WC_NID_X9_62_prime256v1;
14838
            case ECC_SECP112R1_OID:
14839
                return WC_NID_secp112r1;
14840
            case ECC_SECP112R2_OID:
14841
                return WC_NID_secp112r2;
14842
            case ECC_SECP128R1_OID:
14843
                return WC_NID_secp128r1;
14844
            case ECC_SECP128R2_OID:
14845
                return WC_NID_secp128r2;
14846
            case ECC_SECP160R1_OID:
14847
                return WC_NID_secp160r1;
14848
            case ECC_SECP160R2_OID:
14849
                return WC_NID_secp160r2;
14850
            case ECC_SECP224R1_OID:
14851
                return WC_NID_secp224r1;
14852
            case ECC_SECP384R1_OID:
14853
                return WC_NID_secp384r1;
14854
            case ECC_SECP521R1_OID:
14855
                return WC_NID_secp521r1;
14856
            case ECC_SECP160K1_OID:
14857
                return WC_NID_secp160k1;
14858
            case ECC_SECP192K1_OID:
14859
                return WC_NID_secp192k1;
14860
            case ECC_SECP224K1_OID:
14861
                return WC_NID_secp224k1;
14862
            case ECC_SECP256K1_OID:
14863
                return WC_NID_secp256k1;
14864
            case ECC_BRAINPOOLP160R1_OID:
14865
                return WC_NID_brainpoolP160r1;
14866
            case ECC_BRAINPOOLP192R1_OID:
14867
                return WC_NID_brainpoolP192r1;
14868
            case ECC_BRAINPOOLP224R1_OID:
14869
                return WC_NID_brainpoolP224r1;
14870
            case ECC_BRAINPOOLP256R1_OID:
14871
                return WC_NID_brainpoolP256r1;
14872
            case ECC_BRAINPOOLP320R1_OID:
14873
                return WC_NID_brainpoolP320r1;
14874
            case ECC_BRAINPOOLP384R1_OID:
14875
                return WC_NID_brainpoolP384r1;
14876
            case ECC_BRAINPOOLP512R1_OID:
14877
                return WC_NID_brainpoolP512r1;
14878
            }
14879
            break;
14880
    #endif /* HAVE_ECC */
14881
14882
        /* oidBlkType */
14883
        case oidBlkType:
14884
            switch (oid) {
14885
            #ifdef WOLFSSL_AES_128
14886
                case AES128CBCb:
14887
                    return AES128CBCb;
14888
            #endif
14889
            #ifdef WOLFSSL_AES_192
14890
                case AES192CBCb:
14891
                    return AES192CBCb;
14892
            #endif
14893
            #ifdef WOLFSSL_AES_256
14894
                case AES256CBCb:
14895
                    return AES256CBCb;
14896
            #endif
14897
            #ifndef NO_DES3
14898
                case DESb:
14899
                    return WC_NID_des;
14900
                case DES3b:
14901
                    return WC_NID_des3;
14902
            #endif
14903
            }
14904
            break;
14905
14906
    #ifdef HAVE_OCSP
14907
        case oidOcspType:
14908
            switch (oid) {
14909
                case OCSP_BASIC_OID:
14910
                    return WC_NID_id_pkix_OCSP_basic;
14911
                case OCSP_NONCE_OID:
14912
                    return OCSP_NONCE_OID;
14913
            }
14914
            break;
14915
    #endif /* HAVE_OCSP */
14916
14917
        /* oidCertExtType */
14918
        case oidCertExtType:
14919
            switch (oid) {
14920
                case BASIC_CA_OID:
14921
                    return WC_NID_basic_constraints;
14922
                case ALT_NAMES_OID:
14923
                    return WC_NID_subject_alt_name;
14924
                case CRL_DIST_OID:
14925
                    return WC_NID_crl_distribution_points;
14926
                case AUTH_INFO_OID:
14927
                    return WC_NID_info_access;
14928
                case AUTH_KEY_OID:
14929
                    return WC_NID_authority_key_identifier;
14930
                case SUBJ_KEY_OID:
14931
                    return WC_NID_subject_key_identifier;
14932
                case INHIBIT_ANY_OID:
14933
                    return WC_NID_inhibit_any_policy;
14934
                case KEY_USAGE_OID:
14935
                    return WC_NID_key_usage;
14936
                case NAME_CONS_OID:
14937
                    return WC_NID_name_constraints;
14938
                case CERT_POLICY_OID:
14939
                    return WC_NID_certificate_policies;
14940
                case EXT_KEY_USAGE_OID:
14941
                    return WC_NID_ext_key_usage;
14942
            }
14943
            break;
14944
14945
        /* oidCertAuthInfoType */
14946
        case oidCertAuthInfoType:
14947
            switch (oid) {
14948
                case AIA_OCSP_OID:
14949
                    return WC_NID_ad_OCSP;
14950
                case AIA_CA_ISSUER_OID:
14951
                    return WC_NID_ad_ca_issuers;
14952
            }
14953
            break;
14954
14955
        /* oidCertPolicyType */
14956
        case oidCertPolicyType:
14957
            switch (oid) {
14958
                case CP_ANY_OID:
14959
                    return WC_NID_any_policy;
14960
            }
14961
            break;
14962
14963
        /* oidCertAltNameType */
14964
        case oidCertAltNameType:
14965
            switch (oid) {
14966
                case HW_NAME_OID:
14967
                    return WC_NID_hw_name_oid;
14968
            }
14969
            break;
14970
14971
        /* oidCertKeyUseType */
14972
        case oidCertKeyUseType:
14973
            switch (oid) {
14974
                case EKU_ANY_OID:
14975
                    return WC_NID_anyExtendedKeyUsage;
14976
                case EKU_SERVER_AUTH_OID:
14977
                    return EKU_SERVER_AUTH_OID;
14978
                case EKU_CLIENT_AUTH_OID:
14979
                    return EKU_CLIENT_AUTH_OID;
14980
                case EKU_OCSP_SIGN_OID:
14981
                    return EKU_OCSP_SIGN_OID;
14982
            }
14983
            break;
14984
14985
        /* oidKdfType */
14986
        case oidKdfType:
14987
            switch (oid) {
14988
                case PBKDF2_OID:
14989
                    return PBKDF2_OID;
14990
            }
14991
            break;
14992
14993
        /* oidPBEType */
14994
        case oidPBEType:
14995
            switch (oid) {
14996
                case PBE_SHA1_RC4_128:
14997
                    return PBE_SHA1_RC4_128;
14998
                case PBE_SHA1_DES:
14999
                    return PBE_SHA1_DES;
15000
                case PBE_SHA1_DES3:
15001
                    return PBE_SHA1_DES3;
15002
            }
15003
            break;
15004
15005
        /* oidKeyWrapType */
15006
        case oidKeyWrapType:
15007
            switch (oid) {
15008
            #ifdef WOLFSSL_AES_128
15009
                case AES128_WRAP:
15010
                    return AES128_WRAP;
15011
            #endif
15012
            #ifdef WOLFSSL_AES_192
15013
                case AES192_WRAP:
15014
                    return AES192_WRAP;
15015
            #endif
15016
            #ifdef WOLFSSL_AES_256
15017
                case AES256_WRAP:
15018
                    return AES256_WRAP;
15019
            #endif
15020
            }
15021
            break;
15022
15023
        /* oidCmsKeyAgreeType */
15024
        case oidCmsKeyAgreeType:
15025
            switch (oid) {
15026
                #ifndef NO_SHA
15027
                case dhSinglePass_stdDH_sha1kdf_scheme:
15028
                    return dhSinglePass_stdDH_sha1kdf_scheme;
15029
                #endif
15030
                #ifdef WOLFSSL_SHA224
15031
                case dhSinglePass_stdDH_sha224kdf_scheme:
15032
                    return dhSinglePass_stdDH_sha224kdf_scheme;
15033
                #endif
15034
                #ifndef NO_SHA256
15035
                case dhSinglePass_stdDH_sha256kdf_scheme:
15036
                    return dhSinglePass_stdDH_sha256kdf_scheme;
15037
                #endif
15038
                #ifdef WOLFSSL_SHA384
15039
                case dhSinglePass_stdDH_sha384kdf_scheme:
15040
                    return dhSinglePass_stdDH_sha384kdf_scheme;
15041
                #endif
15042
                #ifdef WOLFSSL_SHA512
15043
                case dhSinglePass_stdDH_sha512kdf_scheme:
15044
                    return dhSinglePass_stdDH_sha512kdf_scheme;
15045
                #endif
15046
            }
15047
            break;
15048
15049
#ifdef WOLFSSL_CERT_REQ
15050
        case oidCsrAttrType:
15051
            switch (oid) {
15052
                case PKCS9_CONTENT_TYPE_OID:
15053
                    return WC_NID_pkcs9_contentType;
15054
                case CHALLENGE_PASSWORD_OID:
15055
                    return WC_NID_pkcs9_challengePassword;
15056
                case SERIAL_NUMBER_OID:
15057
                    return WC_NID_serialNumber;
15058
                case USER_ID_OID:
15059
                    return WC_NID_userId;
15060
            }
15061
            break;
15062
#endif
15063
15064
        default:
15065
            WOLFSSL_MSG("OID not in table");
15066
    }
15067
    /* If not found in above switch then try the table */
15068
    for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
15069
        if (wolfssl_object_info[i].id == (int)oid) {
15070
            return wolfssl_object_info[i].nid;
15071
        }
15072
    }
15073
15074
    return WOLFSSL_FATAL_ERROR;
15075
}
15076
15077
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
15078
15079
#if defined(OPENSSL_EXTRA)
15080
15081
/* frees all nodes in the current threads error queue
15082
 *
15083
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
15084
 *     current threads queue will be free'd.
15085
 */
15086
void wolfSSL_ERR_remove_state(unsigned long id)
15087
{
15088
    WOLFSSL_ENTER("wolfSSL_ERR_remove_state");
15089
    (void)id;
15090
    if (wc_ERR_remove_state() != 0) {
15091
        WOLFSSL_MSG("Error with removing the state");
15092
    }
15093
}
15094
15095
#endif /* OPENSSL_EXTRA */
15096
15097
15098
#if defined(OPENSSL_EXTRA)
15099
/* wolfSSL_THREADID_current is provided as a compat API with
15100
 * CRYPTO_THREADID_current to register current thread id into given id object.
15101
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
15102
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
15103
 * like as existing wolfSSL_THREADID_set_numeric.
15104
 */
15105
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
15106
{
15107
    (void)id;
15108
    return;
15109
}
15110
/* wolfSSL_THREADID_hash is provided as a compatible API with
15111
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
15112
 * specified thread id. However, CRYPTO_THREADID_hash API has been
15113
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
15114
 * This API only works as a stub to returns 0. This behavior is
15115
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
15116
 */
15117
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
15118
{
15119
    (void)id;
15120
    return 0UL;
15121
}
15122
15123
/**
15124
 * Set security level (wolfSSL doesn't support setting the security level).
15125
 *
15126
 * The security level can only be set through a system wide crypto-policy
15127
 * with wolfSSL_crypto_policy_enable().
15128
 *
15129
 * @param ctx  a pointer to WOLFSSL_CTX structure
15130
 * @param level security level
15131
 */
15132
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
15133
{
15134
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
15135
    (void)ctx;
15136
    (void)level;
15137
}
15138
15139
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
15140
{
15141
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
15142
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
15143
    if (ctx == NULL) {
15144
        return BAD_FUNC_ARG;
15145
    }
15146
15147
    return ctx->secLevel;
15148
    #else
15149
    (void)ctx;
15150
    return 0;
15151
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
15152
}
15153
15154
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
15155
/*
15156
 * This API accepts a user callback which puts key-log records into
15157
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
15158
 * each SSL object on its creation timing.
15159
 */
15160
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
15161
    wolfSSL_CTX_keylog_cb_func cb)
15162
{
15163
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
15164
    /* stores the callback into WOLFSSL_CTX */
15165
    if (ctx != NULL) {
15166
        ctx->keyLogCb = cb;
15167
    }
15168
}
15169
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
15170
    const WOLFSSL_CTX* ctx)
15171
{
15172
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
15173
    if (ctx != NULL)
15174
        return ctx->keyLogCb;
15175
    return NULL;
15176
}
15177
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
15178
15179
#endif /* OPENSSL_EXTRA */
15180
15181
#ifdef WOLFSSL_THREADED_CRYPT
15182
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
15183
{
15184
    ThreadCrypt* encrypt;
15185
15186
    if (ssl == NULL) {
15187
        return 0;
15188
    }
15189
15190
    encrypt = &ssl->buffers.encrypt[idx];
15191
    return (encrypt->avail == 0) && (encrypt->done == 0);
15192
}
15193
15194
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
15195
{
15196
    ThreadCrypt* encrypt;
15197
15198
    if (ssl == NULL) {
15199
        return 1;
15200
    }
15201
15202
    encrypt = &ssl->buffers.encrypt[idx];
15203
    return encrypt->stop;
15204
}
15205
15206
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
15207
{
15208
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
15209
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
15210
15211
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
15212
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
15213
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
15214
        word32 encSz = encrypt->buffer.length - encrypt->offset;
15215
15216
        ret =
15217
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
15218
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
15219
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
15220
              wc_AesGcmEncrypt_ex
15221
#else
15222
              wc_AesGcmEncrypt
15223
#endif
15224
              (encrypt->encrypt.aes,
15225
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
15226
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
15227
               encrypt->nonce, AESGCM_NONCE_SZ,
15228
               out + encSz - ssl->specs.aead_mac_size,
15229
               ssl->specs.aead_mac_size,
15230
               encrypt->additional, AEAD_AUTH_DATA_SZ);
15231
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
15232
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
15233
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
15234
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
15235
#endif
15236
        encrypt->done = 1;
15237
    }
15238
15239
    return ret;
15240
}
15241
15242
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
15243
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
15244
{
15245
    int ret = 0;
15246
15247
    if (ssl == NULL) {
15248
        ret = BAD_FUNC_ARG;
15249
    }
15250
    else {
15251
        ssl->buffers.encrypt[idx].signal = signal;
15252
        ssl->buffers.encrypt[idx].signalCtx = ctx;
15253
    }
15254
15255
    return ret;
15256
}
15257
#endif
15258
15259
15260
#ifndef NO_CERT
15261
#define WOLFSSL_X509_INCLUDED
15262
#include "src/x509.c"
15263
#endif
15264
15265
/*******************************************************************************
15266
 * START OF standard C library wrapping APIs
15267
 ******************************************************************************/
15268
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
15269
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
15270
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
15271
     defined(WOLFSSL_OPENSSH)))
15272
#ifndef NO_WOLFSSL_STUB
15273
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
15274
                                void *(*r) (void *, size_t, const char *,
15275
                                            int), void (*f) (void *))
15276
{
15277
    (void) m;
15278
    (void) r;
15279
    (void) f;
15280
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
15281
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
15282
15283
    return WOLFSSL_FAILURE;
15284
}
15285
#endif
15286
#endif
15287
15288
#if defined(OPENSSL_EXTRA)
15289
15290
/**
15291
 * free allocated memory resource
15292
 * @param str  a pointer to resource to be freed
15293
 * @param file dummy argument
15294
 * @param line dummy argument
15295
 */
15296
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
15297
{
15298
    (void)file;
15299
    (void)line;
15300
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
15301
}
15302
/**
15303
 * allocate memory with size of num
15304
 * @param num  size of memory allocation to be malloced
15305
 * @param file dummy argument
15306
 * @param line dummy argument
15307
 * @return a pointer to allocated memory on succssesful, otherwise NULL
15308
 */
15309
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
15310
{
15311
    (void)file;
15312
    (void)line;
15313
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
15314
}
15315
15316
#endif
15317
15318
/*******************************************************************************
15319
 * END OF standard C library wrapping APIs
15320
 ******************************************************************************/
15321
15322
/*******************************************************************************
15323
 * START OF EX_DATA APIs
15324
 ******************************************************************************/
15325
#ifdef HAVE_EX_DATA
15326
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
15327
{
15328
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
15329
}
15330
15331
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
15332
{
15333
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
15334
#ifdef MAX_EX_DATA
15335
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15336
        return ex_data->ex_data[idx];
15337
    }
15338
#else
15339
    (void)ex_data;
15340
    (void)idx;
15341
#endif
15342
    return NULL;
15343
}
15344
15345
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
15346
    void *data)
15347
{
15348
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
15349
#ifdef MAX_EX_DATA
15350
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15351
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15352
        if (ex_data->ex_data_cleanup_routines[idx]) {
15353
            /* call cleanup then remove cleanup callback,
15354
             * since different value is being set */
15355
            if (ex_data->ex_data[idx])
15356
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
15357
            ex_data->ex_data_cleanup_routines[idx] = NULL;
15358
        }
15359
#endif
15360
        ex_data->ex_data[idx] = data;
15361
        return WOLFSSL_SUCCESS;
15362
    }
15363
#else
15364
    (void)ex_data;
15365
    (void)idx;
15366
    (void)data;
15367
#endif
15368
    return WOLFSSL_FAILURE;
15369
}
15370
15371
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15372
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
15373
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
15374
    int idx,
15375
    void *data,
15376
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
15377
{
15378
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
15379
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15380
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
15381
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
15382
        ex_data->ex_data[idx] = data;
15383
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
15384
        return WOLFSSL_SUCCESS;
15385
    }
15386
    return WOLFSSL_FAILURE;
15387
}
15388
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
15389
#endif /* HAVE_EX_DATA */
15390
15391
#ifdef HAVE_EX_DATA_CRYPTO
15392
/**
15393
 * Issues unique index for the class specified by class_index.
15394
 * Other parameter except class_index are ignored.
15395
 * Currently, following class_index are accepted:
15396
 *  - WOLF_CRYPTO_EX_INDEX_SSL
15397
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
15398
 *  - WOLF_CRYPTO_EX_INDEX_X509
15399
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
15400
 * @param argp  parameters to be saved
15401
 * @param argl  parameters to be saved
15402
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
15403
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
15404
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
15405
 * @return index value grater or equal to zero on success, -1 on failure.
15406
 */
15407
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
15408
                                           WOLFSSL_CRYPTO_EX_new* new_func,
15409
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
15410
                                           WOLFSSL_CRYPTO_EX_free* free_func)
15411
{
15412
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
15413
15414
    return wolfssl_local_get_ex_new_index(class_index, argl, argp, new_func,
15415
            dup_func, free_func);
15416
}
15417
#endif /* HAVE_EX_DATA_CRYPTO */
15418
15419
/*******************************************************************************
15420
 * END OF EX_DATA APIs
15421
 ******************************************************************************/
15422
15423
/*******************************************************************************
15424
 * START OF BUF_MEM API
15425
 ******************************************************************************/
15426
15427
#if defined(OPENSSL_EXTRA)
15428
15429
/* Begin functions for openssl/buffer.h */
15430
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
15431
{
15432
    WOLFSSL_BUF_MEM* buf;
15433
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
15434
                                                        DYNAMIC_TYPE_OPENSSL);
15435
    if (buf) {
15436
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
15437
    }
15438
    return buf;
15439
}
15440
15441
/* non-compat API returns length of buffer on success */
15442
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
15443
        char zeroFill)
15444
{
15445
    size_t mx;
15446
    char* tmp;
15447
15448
    /* verify provided arguments. The return value is an int holding the
15449
     * resulting length, so reject any len that cannot be represented as a
15450
     * non-negative int. This also prevents truncating size_t to int. */
15451
    if (buf == NULL || len > (size_t)WC_MAX_SINT_OF(int)) {
15452
        return 0; /* BAD_FUNC_ARG; */
15453
    }
15454
15455
    /* check to see if fits in existing length */
15456
    if (buf->length > len) {
15457
        buf->length = len;
15458
        return (int)len;
15459
    }
15460
15461
    /* check to see if fits in max buffer */
15462
    if (buf->max >= len) {
15463
        if (buf->data != NULL && zeroFill) {
15464
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
15465
        }
15466
        buf->length = len;
15467
        return (int)len;
15468
    }
15469
15470
    /* expand size, to handle growth */
15471
    mx = (len + 3) / 3 * 4;
15472
15473
#ifdef WOLFSSL_NO_REALLOC
15474
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
15475
    if (tmp != NULL && buf->data != NULL) {
15476
       /* only the existing content is valid in the old buffer; copying
15477
        * len_int (the new, larger size) would read past buf->max */
15478
       XMEMCPY(tmp, buf->data, buf->length);
15479
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
15480
       buf->data = NULL;
15481
    }
15482
#else
15483
    /* use realloc */
15484
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
15485
#endif
15486
15487
    if (tmp == NULL) {
15488
        return 0; /* ERR_R_MALLOC_FAILURE; */
15489
    }
15490
    buf->data = tmp;
15491
15492
    buf->max = mx;
15493
    if (zeroFill)
15494
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
15495
    buf->length = len;
15496
15497
    return (int)len;
15498
15499
}
15500
15501
/* returns length of buffer on success */
15502
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
15503
{
15504
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
15505
}
15506
15507
/* non-compat API returns length of buffer on success */
15508
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
15509
{
15510
    char* tmp;
15511
    size_t mx;
15512
15513
    /* verify provided arguments. The return value is an int, so reject any
15514
     * len that cannot be represented as a positive int. */
15515
    if (buf == NULL || len == 0 || len > (size_t)WC_MAX_SINT_OF(int)) {
15516
        return 0; /* BAD_FUNC_ARG; */
15517
    }
15518
15519
    if (len == buf->length)
15520
        return (int)len;
15521
15522
    if (len > buf->length)
15523
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
15524
15525
    /* expand size, to handle growth */
15526
    mx = (len + 3) / 3 * 4;
15527
15528
    /* We want to shrink the internal buffer */
15529
#ifdef WOLFSSL_NO_REALLOC
15530
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
15531
    if (tmp != NULL && buf->data != NULL)
15532
    {
15533
        XMEMCPY(tmp, buf->data, len);
15534
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
15535
        buf->data = NULL;
15536
    }
15537
#else
15538
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
15539
#endif
15540
15541
    if (tmp == NULL)
15542
        return 0;
15543
15544
    buf->data = tmp;
15545
    buf->length = len;
15546
    buf->max = mx;
15547
15548
    return (int)len;
15549
}
15550
15551
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
15552
{
15553
    if (buf) {
15554
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
15555
        buf->data = NULL;
15556
        buf->max = 0;
15557
        buf->length = 0;
15558
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
15559
    }
15560
}
15561
/* End Functions for openssl/buffer.h */
15562
15563
#endif /* OPENSSL_EXTRA */
15564
15565
/*******************************************************************************
15566
 * END OF BUF_MEM API
15567
 ******************************************************************************/
15568
15569
#define WOLFSSL_CONF_INCLUDED
15570
#include <src/conf.c>
15571
15572
/*******************************************************************************
15573
 * START OF RAND API
15574
 ******************************************************************************/
15575
15576
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
15577
static int wolfSSL_RAND_InitMutex(void)
15578
{
15579
#ifndef WOLFSSL_MUTEX_INITIALIZER
15580
    if (gRandMethodsInit == 0) {
15581
        if (wc_InitMutex(&gRandMethodMutex) != 0) {
15582
            WOLFSSL_MSG("Bad Init Mutex rand methods");
15583
            return BAD_MUTEX_E;
15584
        }
15585
        gRandMethodsInit = 1;
15586
    }
15587
#endif
15588
    return 0;
15589
}
15590
#endif
15591
15592
#ifdef OPENSSL_EXTRA
15593
15594
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
15595
    ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST))
15596
/* In older FIPS bundles add check for reseed here since it does not exist in
15597
 * the older random.c certified files. */
15598
static pid_t currentRandPid = 0;
15599
#endif
15600
15601
/* Checks if the global RNG has been created. If not then one is created.
15602
 *
15603
 * Returns WOLFSSL_SUCCESS when no error is encountered.
15604
 */
15605
int wolfSSL_RAND_Init(void)
15606
{
15607
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
15608
#ifdef HAVE_GLOBAL_RNG
15609
    if (wc_LockMutex(&globalRNGMutex) == 0) {
15610
        if (initGlobalRNG == 0) {
15611
            ret = wc_InitRng(&globalRNG);
15612
            if (ret == 0) {
15613
            #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
15614
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
15615
                 defined(HAVE_SELFTEST))
15616
15617
                currentRandPid = getpid();
15618
            #endif
15619
                initGlobalRNG = 1;
15620
                ret = WOLFSSL_SUCCESS;
15621
            }
15622
        }
15623
        else {
15624
            /* GlobalRNG is already initialized */
15625
            ret = WOLFSSL_SUCCESS;
15626
        }
15627
15628
        wc_UnLockMutex(&globalRNGMutex);
15629
    }
15630
#endif
15631
    return ret;
15632
}
15633
15634
15635
/* WOLFSSL_SUCCESS on ok */
15636
int wolfSSL_RAND_seed(const void* seed, int len)
15637
{
15638
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
15639
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
15640
        if (gRandMethods && gRandMethods->seed) {
15641
            int ret = gRandMethods->seed(seed, len);
15642
            wc_UnLockMutex(&gRandMethodMutex);
15643
            return ret;
15644
        }
15645
        wc_UnLockMutex(&gRandMethodMutex);
15646
    }
15647
#else
15648
    (void)seed;
15649
    (void)len;
15650
#endif
15651
15652
    /* Make sure global shared RNG (globalRNG) is initialized */
15653
    return wolfSSL_RAND_Init();
15654
}
15655
15656
15657
/* Returns the path for reading seed data from.
15658
 * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
15659
 *
15660
 * Note uses stdlib by default unless XGETENV macro is overwritten
15661
 *
15662
 * fname buffer to hold path
15663
 * len   length of fname buffer
15664
 *
15665
 * Returns a pointer to fname on success and NULL on failure
15666
 */
15667
const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
15668
{
15669
#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV)
15670
    char* rt;
15671
15672
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
15673
15674
    if (fname == NULL) {
15675
        return NULL;
15676
    }
15677
15678
    XMEMSET(fname, 0, len);
15679
15680
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
15681
    if ((rt = XGETENV("RANDFILE")) != NULL) {
15682
        if (len > XSTRLEN(rt)) {
15683
            XMEMCPY(fname, rt, XSTRLEN(rt));
15684
        }
15685
        else {
15686
            WOLFSSL_MSG("RANDFILE too large for buffer");
15687
            rt = NULL;
15688
        }
15689
    }
15690
/* // NOLINTEND(concurrency-mt-unsafe) */
15691
15692
    /* $RANDFILE was not set or is too large, check $HOME */
15693
    if (rt == NULL) {
15694
        const char ap[] = "/.rnd";
15695
15696
        WOLFSSL_MSG("Environment variable RANDFILE not set");
15697
15698
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
15699
        if ((rt = XGETENV("HOME")) == NULL) {
15700
            #ifdef XALTHOMEVARNAME
15701
            if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) {
15702
                WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME
15703
                            " not set");
15704
                return NULL;
15705
            }
15706
            #else
15707
            WOLFSSL_MSG("Environment variable HOME not set");
15708
            return NULL;
15709
            #endif
15710
        }
15711
/* // NOLINTEND(concurrency-mt-unsafe) */
15712
15713
        if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
15714
            fname[0] = '\0';
15715
            XSTRNCAT(fname, rt, len);
15716
            XSTRNCAT(fname, ap, len - XSTRLEN(rt));
15717
            return fname;
15718
        }
15719
        else {
15720
            WOLFSSL_MSG("Path too large for buffer");
15721
            return NULL;
15722
        }
15723
    }
15724
15725
    return fname;
15726
#else
15727
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
15728
    WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, "
15729
                "not compiled in");
15730
    (void)fname;
15731
    (void)len;
15732
    return NULL;
15733
#endif
15734
}
15735
15736
15737
#ifndef WOLFSSL_RAND_WRITE_FILE_BUF_SZ
15738
#define WOLFSSL_RAND_WRITE_FILE_BUF_SZ 1024
15739
#endif
15740
/* Writes WOLFSSL_RAND_WRITE_FILE_BUF_SZ bytes (1024 by default) from the RNG
15741
 * to the given file name.
15742
 *
15743
 * fname name of file to write to
15744
 *
15745
 * Returns the number of bytes written
15746
 */
15747
int wolfSSL_RAND_write_file(const char* fname)
15748
{
15749
    int bytes = 0;
15750
15751
    WOLFSSL_ENTER("wolfSSL_RAND_write_file");
15752
15753
    if (fname == NULL) {
15754
        return WOLFSSL_FAILURE;
15755
    }
15756
15757
#ifndef NO_FILESYSTEM
15758
    {
15759
    #ifndef WOLFSSL_SMALL_STACK
15760
        unsigned char buf[WOLFSSL_RAND_WRITE_FILE_BUF_SZ];
15761
    #else
15762
        unsigned char* buf = (unsigned char *)XMALLOC(
15763
            WOLFSSL_RAND_WRITE_FILE_BUF_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15764
        if (buf == NULL) {
15765
            WOLFSSL_MSG("malloc failed");
15766
            return WOLFSSL_FAILURE;
15767
        }
15768
    #endif
15769
        bytes = WOLFSSL_RAND_WRITE_FILE_BUF_SZ;
15770
15771
        if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
15772
            WOLFSSL_MSG("No RNG to use");
15773
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15774
            return 0;
15775
        }
15776
15777
        if (wc_LockMutex(&globalRNGMutex) != 0) {
15778
            WOLFSSL_MSG("Bad Lock Mutex rng");
15779
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15780
            return 0;
15781
        }
15782
15783
        if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) {
15784
            wc_UnLockMutex(&globalRNGMutex);
15785
            WOLFSSL_MSG("Error generating random buffer");
15786
            bytes = 0;
15787
        }
15788
        else {
15789
            XFILE f;
15790
15791
            wc_UnLockMutex(&globalRNGMutex);
15792
15793
        #ifdef WOLFSSL_CHECK_MEM_ZERO
15794
            wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
15795
        #endif
15796
15797
            f = XFOPEN(fname, "wb");
15798
            if (f == XBADFILE) {
15799
                WOLFSSL_MSG("Error opening the file");
15800
                bytes = 0;
15801
            }
15802
            else {
15803
                size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f);
15804
                bytes = (int)bytes_written;
15805
                XFCLOSE(f);
15806
            }
15807
        }
15808
        /* wipe the whole buffer, not just (word32)bytes: error paths set
15809
         * bytes = 0 but the buffer may still hold generated random data */
15810
        ForceZero(buf, WOLFSSL_RAND_WRITE_FILE_BUF_SZ);
15811
    #ifdef WOLFSSL_SMALL_STACK
15812
        XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15813
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
15814
        wc_MemZero_Check(buf, sizeof(buf));
15815
    #endif
15816
    }
15817
#endif
15818
15819
    return bytes;
15820
}
15821
15822
#ifndef FREERTOS_TCP
15823
15824
/* These constant values are protocol values made by egd */
15825
#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \
15826
    !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \
15827
    defined(HAVE_SYS_UN_H)
15828
    #define WOLFSSL_EGD_NBLOCK 0x01
15829
    #include <sys/un.h>
15830
#endif
15831
15832
/* This collects entropy from the path nm and seeds the global PRNG with it.
15833
 *
15834
 * nm is the file path to the egd server
15835
 *
15836
 * Returns the number of bytes read.
15837
 */
15838
int wolfSSL_RAND_egd(const char* nm)
15839
{
15840
#ifdef WOLFSSL_EGD_NBLOCK
15841
    struct sockaddr_un rem;
15842
    int fd;
15843
    int ret = WOLFSSL_SUCCESS;
15844
    word32 bytes = 0;
15845
    word32 idx   = 0;
15846
#ifndef WOLFSSL_SMALL_STACK
15847
    unsigned char buf[256];
15848
#else
15849
    unsigned char* buf;
15850
    buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15851
    if (buf == NULL) {
15852
        WOLFSSL_MSG("Not enough memory");
15853
        return WOLFSSL_FATAL_ERROR;
15854
    }
15855
#endif
15856
15857
    XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
15858
    if (nm == NULL) {
15859
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15860
        return WOLFSSL_FATAL_ERROR;
15861
    }
15862
15863
    fd = wc_socket_cloexec(AF_UNIX, SOCK_STREAM, 0);
15864
    if (fd < 0) {
15865
        WOLFSSL_MSG("Error creating socket");
15866
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15867
        return WOLFSSL_FATAL_ERROR;
15868
    }
15869
    rem.sun_family = AF_UNIX;
15870
    XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
15871
    rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
15872
15873
    /* connect to egd server */
15874
    if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
15875
        WOLFSSL_MSG("error connecting to egd server");
15876
        ret = WOLFSSL_FATAL_ERROR;
15877
    }
15878
15879
#ifdef WOLFSSL_CHECK_MEM_ZERO
15880
    if (ret == WOLFSSL_SUCCESS) {
15881
        wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
15882
    }
15883
#endif
15884
    while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
15885
        buf[idx]     = WOLFSSL_EGD_NBLOCK;
15886
        buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
15887
        ret = (int)write(fd, buf + idx, 2);
15888
        if (ret != 2) {
15889
            if (errno == EAGAIN) {
15890
                ret = WOLFSSL_SUCCESS;
15891
                continue;
15892
            }
15893
            WOLFSSL_MSG("error requesting entropy from egd server");
15894
            ret = WOLFSSL_FATAL_ERROR;
15895
            break;
15896
        }
15897
15898
        /* attempting to read */
15899
        buf[idx] = 0;
15900
        ret = (int)read(fd, buf + idx, 256 - bytes);
15901
        if (ret == 0) {
15902
            WOLFSSL_MSG("error reading entropy from egd server");
15903
            ret = WOLFSSL_FATAL_ERROR;
15904
            break;
15905
        }
15906
        if (ret > 0 && buf[idx] > 0) {
15907
            bytes += buf[idx]; /* egd stores amount sent in first byte */
15908
            if (bytes + idx > 255 || buf[idx] > ret) {
15909
                WOLFSSL_MSG("Buffer error");
15910
                ret = WOLFSSL_FATAL_ERROR;
15911
                break;
15912
            }
15913
            XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
15914
            idx = bytes;
15915
            ret = WOLFSSL_SUCCESS;
15916
            if (bytes >= 255) {
15917
                break;
15918
            }
15919
        }
15920
        else {
15921
            if (errno == EAGAIN || errno == EINTR) {
15922
                WOLFSSL_MSG("EGD would read");
15923
                ret = WOLFSSL_SUCCESS; /* try again */
15924
            }
15925
            else if (buf[idx] == 0) {
15926
                /* if egd returned 0 then there is no more entropy to be had.
15927
                   Do not try more reads. */
15928
                ret = WOLFSSL_SUCCESS;
15929
                break;
15930
            }
15931
            else {
15932
                WOLFSSL_MSG("Error with read");
15933
                ret = WOLFSSL_FATAL_ERROR;
15934
            }
15935
        }
15936
    }
15937
15938
    if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
15939
        /* call to check global RNG is created */
15940
        if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
15941
            WOLFSSL_MSG("Error with initializing global RNG structure");
15942
            ret = WOLFSSL_FATAL_ERROR;
15943
        }
15944
        else if (wc_LockMutex(&globalRNGMutex) != 0) {
15945
            WOLFSSL_MSG("Bad Lock Mutex rng");
15946
            ret = WOLFSSL_FATAL_ERROR;
15947
        }
15948
        else {
15949
            if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
15950
                    != 0) {
15951
                WOLFSSL_MSG("Error with reseeding DRBG structure");
15952
                ret = WOLFSSL_FATAL_ERROR;
15953
            }
15954
            wc_UnLockMutex(&globalRNGMutex);
15955
15956
            #ifdef SHOW_SECRETS
15957
            /* print out entropy found only when no error occurred */
15958
            if (ret == WOLFSSL_SUCCESS) {
15959
                word32 i;
15960
                printf("EGD Entropy = ");
15961
                for (i = 0; i < bytes; i++) {
15962
                    printf("%02X", buf[i]);
15963
                }
15964
                printf("\n");
15965
            }
15966
            #endif
15967
        }
15968
    }
15969
15970
    ForceZero(buf, bytes);
15971
#ifdef WOLFSSL_SMALL_STACK
15972
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15973
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
15974
    wc_MemZero_Check(buf, 256);
15975
#endif
15976
    close(fd);
15977
15978
    if (ret == WOLFSSL_SUCCESS) {
15979
        return (int)bytes;
15980
    }
15981
    else {
15982
        return ret;
15983
    }
15984
#else
15985
    WOLFSSL_MSG("Type of socket needed is not available");
15986
    WOLFSSL_MSG("\tor using mode where DRBG API is not available");
15987
    (void)nm;
15988
15989
    return WOLFSSL_FATAL_ERROR;
15990
#endif /* WOLFSSL_EGD_NBLOCK */
15991
}
15992
15993
#endif /* !FREERTOS_TCP */
15994
15995
void wolfSSL_RAND_Cleanup(void)
15996
{
15997
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
15998
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
15999
        if (gRandMethods && gRandMethods->cleanup)
16000
            gRandMethods->cleanup();
16001
        wc_UnLockMutex(&gRandMethodMutex);
16002
    }
16003
16004
    #ifndef WOLFSSL_MUTEX_INITIALIZER
16005
    if (wc_FreeMutex(&gRandMethodMutex) == 0)
16006
        gRandMethodsInit = 0;
16007
    #endif
16008
#endif
16009
#ifdef HAVE_GLOBAL_RNG
16010
    if (wc_LockMutex(&globalRNGMutex) == 0) {
16011
        if (initGlobalRNG) {
16012
            wc_FreeRng(&globalRNG);
16013
            initGlobalRNG = 0;
16014
        }
16015
        wc_UnLockMutex(&globalRNGMutex);
16016
    }
16017
#endif
16018
}
16019
16020
/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise
16021
 * WOLFSSL_FAILURE */
16022
int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
16023
{
16024
    int ret;
16025
    int hash;
16026
    byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */
16027
16028
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16029
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
16030
        if (gRandMethods && gRandMethods->pseudorand) {
16031
            ret = gRandMethods->pseudorand(buf, num);
16032
            wc_UnLockMutex(&gRandMethodMutex);
16033
            return ret;
16034
        }
16035
        wc_UnLockMutex(&gRandMethodMutex);
16036
    }
16037
#endif
16038
16039
#ifdef WOLFSSL_HAVE_PRF
16040
    #ifndef NO_SHA256
16041
    hash = WC_SHA256;
16042
    #elif defined(WOLFSSL_SHA384)
16043
    hash = WC_SHA384;
16044
    #elif !defined(NO_SHA)
16045
    hash = WC_SHA;
16046
    #elif !defined(NO_MD5)
16047
    hash = WC_MD5;
16048
    #endif
16049
16050
    /* get secret value from source of entropy */
16051
    ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
16052
16053
    /* uses input buffer to seed for pseudo random number generation, each
16054
     * thread will potentially have different results this way */
16055
    if (ret == WOLFSSL_SUCCESS) {
16056
        PRIVATE_KEY_UNLOCK();
16057
        ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
16058
                hash, NULL, INVALID_DEVID);
16059
        PRIVATE_KEY_LOCK();
16060
        ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
16061
    }
16062
#else
16063
    /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
16064
    ret = wolfSSL_RAND_bytes(buf, num);
16065
    (void)hash;
16066
    (void)secret;
16067
#endif
16068
    return ret;
16069
}
16070
16071
/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0
16072
 * on failure */
16073
int wolfSSL_RAND_bytes(unsigned char* buf, int num)
16074
{
16075
    int     ret = 0;
16076
    WC_RNG* rng = NULL;
16077
    WC_DECLARE_VAR(tmpRNG, WC_RNG, 1, 0);
16078
    int initTmpRng = 0;
16079
#ifdef HAVE_GLOBAL_RNG
16080
    int used_global = 0;
16081
#endif
16082
16083
    WOLFSSL_ENTER("wolfSSL_RAND_bytes");
16084
    /* sanity check */
16085
    if (buf == NULL || num < 0)
16086
        /* return code compliant with OpenSSL */
16087
        return 0;
16088
16089
    /* if a RAND callback has been set try and use it */
16090
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16091
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
16092
        if (gRandMethods && gRandMethods->bytes) {
16093
            ret = gRandMethods->bytes(buf, num);
16094
            wc_UnLockMutex(&gRandMethodMutex);
16095
            return ret;
16096
        }
16097
        wc_UnLockMutex(&gRandMethodMutex);
16098
    }
16099
#endif
16100
#ifdef HAVE_GLOBAL_RNG
16101
    if (initGlobalRNG) {
16102
        if (wc_LockMutex(&globalRNGMutex) != 0) {
16103
            WOLFSSL_MSG("Bad Lock Mutex rng");
16104
            return ret;
16105
        }
16106
        /* the above access to initGlobalRNG is racey -- recheck it now that we
16107
         * have the lock.
16108
         */
16109
        if (initGlobalRNG) {
16110
        #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
16111
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
16112
                 defined(HAVE_SELFTEST))
16113
            pid_t p;
16114
16115
            p = getpid();
16116
            if (p != currentRandPid) {
16117
                wc_UnLockMutex(&globalRNGMutex);
16118
                if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) {
16119
                    WOLFSSL_MSG("Issue with check pid and reseed");
16120
                    ret = WOLFSSL_FAILURE;
16121
                }
16122
16123
                /* reclaim lock after wolfSSL_RAND_poll */
16124
                if (wc_LockMutex(&globalRNGMutex) != 0) {
16125
                    WOLFSSL_MSG("Bad Lock Mutex rng");
16126
                    return ret;
16127
                }
16128
                currentRandPid = p;
16129
            }
16130
        #endif
16131
            rng = &globalRNG;
16132
            used_global = 1;
16133
        }
16134
        else {
16135
            wc_UnLockMutex(&globalRNGMutex);
16136
        }
16137
    }
16138
16139
    if (used_global == 0)
16140
#endif
16141
    {
16142
        WC_ALLOC_VAR_EX(tmpRNG, WC_RNG, 1, NULL, DYNAMIC_TYPE_RNG,
16143
            return ret);
16144
        if (wc_InitRng(tmpRNG) == 0) {
16145
            rng = tmpRNG;
16146
            initTmpRng = 1;
16147
        }
16148
    }
16149
    if (rng) {
16150
        /* handles size greater than RNG_MAX_BLOCK_LEN */
16151
        int blockCount = num / RNG_MAX_BLOCK_LEN;
16152
16153
        while (blockCount--) {
16154
            ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
16155
            if (ret != 0) {
16156
                WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
16157
                break;
16158
            }
16159
            num -= RNG_MAX_BLOCK_LEN;
16160
            buf += RNG_MAX_BLOCK_LEN;
16161
        }
16162
16163
        if (ret == 0 && num)
16164
            ret = wc_RNG_GenerateBlock(rng, buf, (word32)num);
16165
16166
        if (ret != 0)
16167
            WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
16168
        else
16169
            ret = WOLFSSL_SUCCESS;
16170
    }
16171
16172
#ifdef HAVE_GLOBAL_RNG
16173
    if (used_global == 1)
16174
        wc_UnLockMutex(&globalRNGMutex);
16175
#endif
16176
    if (initTmpRng)
16177
        wc_FreeRng(tmpRNG);
16178
    WC_FREE_VAR_EX(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
16179
16180
    return ret;
16181
}
16182
16183
16184
int wolfSSL_RAND_poll(void)
16185
{
16186
    byte  entropy[16];
16187
    int  ret = 0;
16188
    word32 entropy_sz = 16;
16189
16190
    WOLFSSL_ENTER("wolfSSL_RAND_poll");
16191
    if (initGlobalRNG == 0){
16192
        WOLFSSL_MSG("Global RNG no Init");
16193
        return  WOLFSSL_FAILURE;
16194
    }
16195
16196
    /* lock intentionally covers wc_GenerateSeed as well, since it writes
16197
     * globalRNG.seed; do not narrow this scope or the seed write races */
16198
    if (wc_LockMutex(&globalRNGMutex) != 0) {
16199
        WOLFSSL_MSG("Bad Lock Mutex rng");
16200
        return WOLFSSL_FAILURE;
16201
    }
16202
16203
    ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
16204
    if (ret != 0) {
16205
        WOLFSSL_MSG("Bad wc_GenerateSeed");
16206
        ret = WOLFSSL_FAILURE;
16207
    }
16208
    else {
16209
#ifdef HAVE_HASHDRBG
16210
        ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
16211
        if (ret != 0) {
16212
            WOLFSSL_MSG("Error reseeding DRBG");
16213
            ret = WOLFSSL_FAILURE;
16214
        }
16215
        else {
16216
            ret = WOLFSSL_SUCCESS;
16217
        }
16218
#elif defined(HAVE_INTEL_RDRAND)
16219
        WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without "
16220
                    "HAVE_HASHDRBG");
16221
        ret = WOLFSSL_SUCCESS;
16222
#else
16223
        WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set");
16224
        ret = WOLFSSL_FAILURE;
16225
#endif
16226
    }
16227
16228
    wc_UnLockMutex(&globalRNGMutex);
16229
16230
    return ret;
16231
}
16232
16233
    /* If a valid struct is provided with function pointers, will override
16234
       RAND_seed, bytes, cleanup, add, pseudo_bytes and status.  If a NULL
16235
       pointer is passed in, it will cancel any previous function overrides.
16236
16237
       Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
16238
    int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
16239
    {
16240
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16241
        if (wolfSSL_RAND_InitMutex() == 0 &&
16242
                wc_LockMutex(&gRandMethodMutex) == 0) {
16243
            gRandMethods = methods;
16244
            wc_UnLockMutex(&gRandMethodMutex);
16245
            return WOLFSSL_SUCCESS;
16246
        }
16247
    #else
16248
        (void)methods;
16249
    #endif
16250
        return WOLFSSL_FAILURE;
16251
    }
16252
16253
    /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
16254
    int wolfSSL_RAND_status(void)
16255
    {
16256
        int ret = WOLFSSL_SUCCESS;
16257
        int useGlobalRng = 1;
16258
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16259
        if (wolfSSL_RAND_InitMutex() == 0 &&
16260
                wc_LockMutex(&gRandMethodMutex) == 0) {
16261
            if (gRandMethods && gRandMethods->status) {
16262
                ret = gRandMethods->status();
16263
                useGlobalRng = 0;
16264
            }
16265
            wc_UnLockMutex(&gRandMethodMutex);
16266
        }
16267
        else {
16268
            ret = WOLFSSL_FAILURE;
16269
            useGlobalRng = 0;
16270
        }
16271
    #endif
16272
16273
        /* Drive the global RNG so init / DRBG state failures (mutex
16274
         * acquisition, reseed required, corrupted state) surface to the
16275
         * caller. DRBG output is deterministic between reseeds, so this
16276
         * does not directly probe the entropy source. */
16277
    #ifdef HAVE_GLOBAL_RNG
16278
        if (useGlobalRng) {
16279
            if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
16280
                ret = WOLFSSL_FAILURE;
16281
            }
16282
            else if (wc_LockMutex(&globalRNGMutex) != 0) {
16283
                ret = WOLFSSL_FAILURE;
16284
            }
16285
            else {
16286
                byte b = 0;
16287
                int genRet = wc_RNG_GenerateBlock(&globalRNG, &b, 1);
16288
                wc_UnLockMutex(&globalRNGMutex);
16289
                ForceZero(&b, 1);
16290
                if (genRet != 0)
16291
                    ret = WOLFSSL_FAILURE;
16292
            }
16293
        }
16294
    #endif
16295
        (void)useGlobalRng;
16296
        return ret;
16297
    }
16298
16299
    void wolfSSL_RAND_add(const void* add, int len, double entropy)
16300
    {
16301
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16302
        if (wolfSSL_RAND_InitMutex() == 0 &&
16303
                wc_LockMutex(&gRandMethodMutex) == 0) {
16304
            if (gRandMethods && gRandMethods->add) {
16305
                /* callback has return code, but RAND_add does not */
16306
                (void)gRandMethods->add(add, len, entropy);
16307
            }
16308
            wc_UnLockMutex(&gRandMethodMutex);
16309
        }
16310
    #else
16311
        /* wolfSSL seeds/adds internally, use explicit RNG if you want
16312
           to take control */
16313
        (void)add;
16314
        (void)len;
16315
        (void)entropy;
16316
    #endif
16317
    }
16318
16319
16320
#ifndef NO_WOLFSSL_STUB
16321
void wolfSSL_RAND_screen(void)
16322
{
16323
    WOLFSSL_STUB("RAND_screen");
16324
}
16325
#endif
16326
16327
#ifndef WOLFSSL_RAND_LOAD_FILE_BUF_SZ
16328
#define WOLFSSL_RAND_LOAD_FILE_BUF_SZ 256
16329
#endif
16330
#ifndef WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
16331
#define WOLFSSL_RAND_LOAD_FILE_MAX_BYTES (1L << 20)
16332
#endif
16333
16334
int wolfSSL_RAND_load_file(const char* fname, long len)
16335
{
16336
#if !defined(NO_FILESYSTEM) && defined(HAVE_HASHDRBG)
16337
    XFILE  f;
16338
    long   maxBytes;
16339
    long   readSoFar = 0;
16340
    int    ret = 0;
16341
#ifndef WOLFSSL_SMALL_STACK
16342
    unsigned char buf[WOLFSSL_RAND_LOAD_FILE_BUF_SZ];
16343
#else
16344
    unsigned char* buf;
16345
#endif
16346
16347
    WOLFSSL_ENTER("wolfSSL_RAND_load_file");
16348
16349
    if (fname == NULL)
16350
        return WOLFSSL_FATAL_ERROR;
16351
16352
    /* OpenSSL semantics: RAND_load_file(file, -1) reads up to an
16353
     * implementation-defined maximum. WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
16354
     * caps the read so callers passing -1 to ingest a seed file aren't
16355
     * silently truncated at a small default. */
16356
    maxBytes = (len < 0) ? WOLFSSL_RAND_LOAD_FILE_MAX_BYTES : len;
16357
    if (maxBytes == 0)
16358
        return 0;
16359
16360
    f = XFOPEN(fname, "rb");
16361
    if (f == XBADFILE) {
16362
        WOLFSSL_MSG("RAND_load_file: cannot open file");
16363
        return WOLFSSL_FATAL_ERROR;
16364
    }
16365
16366
#ifdef WOLFSSL_SMALL_STACK
16367
    buf = (unsigned char*)XMALLOC(WOLFSSL_RAND_LOAD_FILE_BUF_SZ, NULL,
16368
        DYNAMIC_TYPE_TMP_BUFFER);
16369
    if (buf == NULL) {
16370
        XFCLOSE(f);
16371
        return WOLFSSL_FATAL_ERROR;
16372
    }
16373
#endif
16374
#ifdef WOLFSSL_CHECK_MEM_ZERO
16375
    wc_MemZero_Add("wolfSSL_RAND_load_file buf", buf,
16376
        WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16377
#endif
16378
16379
    if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
16380
        WOLFSSL_MSG("RAND_load_file: global RNG not available");
16381
        ret = WOLFSSL_FATAL_ERROR;
16382
        goto cleanup;
16383
    }
16384
16385
    while (readSoFar < maxBytes) {
16386
        size_t toRead = (size_t)((maxBytes - readSoFar) <
16387
                WOLFSSL_RAND_LOAD_FILE_BUF_SZ
16388
            ? (maxBytes - readSoFar) : WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16389
        size_t n = XFREAD(buf, 1, toRead, f);
16390
        if (n == 0)
16391
            break;
16392
        if (wc_LockMutex(&globalRNGMutex) != 0) {
16393
            ret = WOLFSSL_FATAL_ERROR;
16394
            break;
16395
        }
16396
        if (wc_RNG_DRBG_Reseed(&globalRNG, buf, (word32)n) != 0) {
16397
            wc_UnLockMutex(&globalRNGMutex);
16398
            WOLFSSL_MSG("RAND_load_file: DRBG reseed failed");
16399
            ret = WOLFSSL_FATAL_ERROR;
16400
            break;
16401
        }
16402
        wc_UnLockMutex(&globalRNGMutex);
16403
        readSoFar += (long)n;
16404
    }
16405
16406
cleanup:
16407
    XFCLOSE(f);
16408
    ForceZero(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16409
#ifdef WOLFSSL_SMALL_STACK
16410
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
16411
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
16412
    wc_MemZero_Check(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16413
#endif
16414
16415
    if (ret < 0)
16416
        return WOLFSSL_FATAL_ERROR;
16417
    return (int)readSoFar;
16418
#else
16419
    /* Without HAVE_HASHDRBG / filesystem support there is no way to feed
16420
     * external entropy to the wolfCrypt RNG; return success so callers
16421
     * in those configurations are not broken. */
16422
    (void)fname;
16423
    if (len == -1)
16424
        return 1024;
16425
    return (int)len;
16426
#endif
16427
}
16428
16429
#endif /* OPENSSL_EXTRA */
16430
16431
/*******************************************************************************
16432
 * END OF RAND API
16433
 ******************************************************************************/
16434
16435
/*******************************************************************************
16436
 * START OF EVP_CIPHER API
16437
 ******************************************************************************/
16438
16439
#ifdef OPENSSL_EXTRA
16440
16441
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
16442
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
16443
    {
16444
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
16445
16446
        if (ctx == NULL) {
16447
            WOLFSSL_MSG("Bad function argument");
16448
            return WOLFSSL_FATAL_ERROR;
16449
        }
16450
16451
        switch (ctx->cipherType) {
16452
#ifndef NO_AES
16453
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
16454
            case WC_AES_128_CBC_TYPE :
16455
            case WC_AES_192_CBC_TYPE :
16456
            case WC_AES_256_CBC_TYPE :
16457
                WOLFSSL_MSG("AES CBC");
16458
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16459
                break;
16460
#endif
16461
#ifdef HAVE_AESGCM
16462
            case WC_AES_128_GCM_TYPE :
16463
            case WC_AES_192_GCM_TYPE :
16464
            case WC_AES_256_GCM_TYPE :
16465
                WOLFSSL_MSG("AES GCM");
16466
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16467
                break;
16468
#endif /* HAVE_AESGCM */
16469
#ifdef HAVE_AESCCM
16470
            case WC_AES_128_CCM_TYPE :
16471
            case WC_AES_192_CCM_TYPE :
16472
            case WC_AES_256_CCM_TYPE :
16473
                WOLFSSL_MSG("AES CCM");
16474
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16475
                break;
16476
#endif /* HAVE_AESCCM */
16477
#ifdef HAVE_AES_ECB
16478
            case WC_AES_128_ECB_TYPE :
16479
            case WC_AES_192_ECB_TYPE :
16480
            case WC_AES_256_ECB_TYPE :
16481
                WOLFSSL_MSG("AES ECB");
16482
                break;
16483
#endif
16484
#ifdef WOLFSSL_AES_COUNTER
16485
            case WC_AES_128_CTR_TYPE :
16486
            case WC_AES_192_CTR_TYPE :
16487
            case WC_AES_256_CTR_TYPE :
16488
                WOLFSSL_MSG("AES CTR");
16489
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
16490
                break;
16491
#endif /* WOLFSSL_AES_COUNTER */
16492
#ifdef WOLFSSL_AES_CFB
16493
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
16494
            case WC_AES_128_CFB1_TYPE:
16495
            case WC_AES_192_CFB1_TYPE:
16496
            case WC_AES_256_CFB1_TYPE:
16497
                WOLFSSL_MSG("AES CFB1");
16498
                break;
16499
            case WC_AES_128_CFB8_TYPE:
16500
            case WC_AES_192_CFB8_TYPE:
16501
            case WC_AES_256_CFB8_TYPE:
16502
                WOLFSSL_MSG("AES CFB8");
16503
                break;
16504
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
16505
            case WC_AES_128_CFB128_TYPE:
16506
            case WC_AES_192_CFB128_TYPE:
16507
            case WC_AES_256_CFB128_TYPE:
16508
                WOLFSSL_MSG("AES CFB128");
16509
                break;
16510
#endif /* WOLFSSL_AES_CFB */
16511
#if defined(WOLFSSL_AES_OFB)
16512
            case WC_AES_128_OFB_TYPE:
16513
            case WC_AES_192_OFB_TYPE:
16514
            case WC_AES_256_OFB_TYPE:
16515
                WOLFSSL_MSG("AES OFB");
16516
                break;
16517
#endif /* WOLFSSL_AES_OFB */
16518
#ifdef WOLFSSL_AES_XTS
16519
            case WC_AES_128_XTS_TYPE:
16520
            case WC_AES_256_XTS_TYPE:
16521
                WOLFSSL_MSG("AES XTS");
16522
                break;
16523
#endif /* WOLFSSL_AES_XTS */
16524
#endif /* NO_AES */
16525
16526
#ifdef HAVE_ARIA
16527
            case WC_ARIA_128_GCM_TYPE :
16528
            case WC_ARIA_192_GCM_TYPE :
16529
            case WC_ARIA_256_GCM_TYPE :
16530
                WOLFSSL_MSG("ARIA GCM");
16531
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
16532
                break;
16533
#endif /* HAVE_ARIA */
16534
16535
#ifndef NO_DES3
16536
            case WC_DES_CBC_TYPE :
16537
                WOLFSSL_MSG("DES CBC");
16538
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
16539
                break;
16540
16541
            case WC_DES_EDE3_CBC_TYPE :
16542
                WOLFSSL_MSG("DES EDE3 CBC");
16543
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
16544
                break;
16545
#endif
16546
#ifdef WOLFSSL_DES_ECB
16547
            case WC_DES_ECB_TYPE :
16548
                WOLFSSL_MSG("DES ECB");
16549
                break;
16550
            case WC_DES_EDE3_ECB_TYPE :
16551
                WOLFSSL_MSG("DES3 ECB");
16552
                break;
16553
#endif
16554
            case WC_ARC4_TYPE :
16555
                WOLFSSL_MSG("ARC4");
16556
                break;
16557
16558
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
16559
            case WC_CHACHA20_POLY1305_TYPE:
16560
                break;
16561
#endif
16562
16563
#ifdef HAVE_CHACHA
16564
            case WC_CHACHA20_TYPE:
16565
                break;
16566
#endif
16567
16568
#ifdef WOLFSSL_SM4_ECB
16569
            case WC_SM4_ECB_TYPE:
16570
                break;
16571
#endif
16572
#ifdef WOLFSSL_SM4_CBC
16573
            case WC_SM4_CBC_TYPE:
16574
                WOLFSSL_MSG("SM4 CBC");
16575
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16576
                break;
16577
#endif
16578
#ifdef WOLFSSL_SM4_CTR
16579
            case WC_SM4_CTR_TYPE:
16580
                WOLFSSL_MSG("SM4 CTR");
16581
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16582
                break;
16583
#endif
16584
#ifdef WOLFSSL_SM4_GCM
16585
            case WC_SM4_GCM_TYPE:
16586
                WOLFSSL_MSG("SM4 GCM");
16587
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16588
                break;
16589
#endif
16590
#ifdef WOLFSSL_SM4_CCM
16591
            case WC_SM4_CCM_TYPE:
16592
                WOLFSSL_MSG("SM4 CCM");
16593
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16594
                break;
16595
#endif
16596
16597
            case WC_NULL_CIPHER_TYPE :
16598
                WOLFSSL_MSG("NULL");
16599
                break;
16600
16601
            default: {
16602
                WOLFSSL_MSG("bad type");
16603
                return WOLFSSL_FATAL_ERROR;
16604
            }
16605
        }
16606
        return WOLFSSL_SUCCESS;
16607
    }
16608
16609
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
16610
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
16611
    {
16612
16613
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
16614
16615
        if (ctx == NULL) {
16616
            WOLFSSL_MSG("Bad function argument");
16617
            return WOLFSSL_FATAL_ERROR;
16618
        }
16619
16620
        switch (ctx->cipherType) {
16621
16622
#ifndef NO_AES
16623
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
16624
            case WC_AES_128_CBC_TYPE :
16625
            case WC_AES_192_CBC_TYPE :
16626
            case WC_AES_256_CBC_TYPE :
16627
                WOLFSSL_MSG("AES CBC");
16628
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16629
                break;
16630
#endif
16631
#ifdef HAVE_AESGCM
16632
            case WC_AES_128_GCM_TYPE :
16633
            case WC_AES_192_GCM_TYPE :
16634
            case WC_AES_256_GCM_TYPE :
16635
                WOLFSSL_MSG("AES GCM");
16636
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16637
                break;
16638
#endif
16639
#ifdef HAVE_AES_ECB
16640
            case WC_AES_128_ECB_TYPE :
16641
            case WC_AES_192_ECB_TYPE :
16642
            case WC_AES_256_ECB_TYPE :
16643
                WOLFSSL_MSG("AES ECB");
16644
                break;
16645
#endif
16646
#ifdef WOLFSSL_AES_COUNTER
16647
            case WC_AES_128_CTR_TYPE :
16648
            case WC_AES_192_CTR_TYPE :
16649
            case WC_AES_256_CTR_TYPE :
16650
                WOLFSSL_MSG("AES CTR");
16651
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16652
                break;
16653
#endif
16654
16655
#endif /* NO_AES */
16656
16657
#ifdef HAVE_ARIA
16658
            case WC_ARIA_128_GCM_TYPE :
16659
            case WC_ARIA_192_GCM_TYPE :
16660
            case WC_ARIA_256_GCM_TYPE :
16661
                WOLFSSL_MSG("ARIA GCM");
16662
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
16663
                break;
16664
#endif /* HAVE_ARIA */
16665
16666
#ifndef NO_DES3
16667
            case WC_DES_CBC_TYPE :
16668
                WOLFSSL_MSG("DES CBC");
16669
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
16670
                break;
16671
16672
            case WC_DES_EDE3_CBC_TYPE :
16673
                WOLFSSL_MSG("DES EDE3 CBC");
16674
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
16675
                break;
16676
#endif
16677
#ifdef WOLFSSL_DES_ECB
16678
            case WC_DES_ECB_TYPE :
16679
                WOLFSSL_MSG("DES ECB");
16680
                break;
16681
            case WC_DES_EDE3_ECB_TYPE :
16682
                WOLFSSL_MSG("DES3 ECB");
16683
                break;
16684
#endif
16685
16686
            case WC_ARC4_TYPE :
16687
                WOLFSSL_MSG("ARC4");
16688
                break;
16689
16690
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
16691
            case WC_CHACHA20_POLY1305_TYPE:
16692
                break;
16693
#endif
16694
16695
#ifdef HAVE_CHACHA
16696
            case WC_CHACHA20_TYPE:
16697
                break;
16698
#endif
16699
16700
#ifdef WOLFSSL_SM4_ECB
16701
            case WC_SM4_ECB_TYPE:
16702
                break;
16703
#endif
16704
#ifdef WOLFSSL_SM4_CBC
16705
            case WC_SM4_CBC_TYPE:
16706
                WOLFSSL_MSG("SM4 CBC");
16707
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16708
                break;
16709
#endif
16710
#ifdef WOLFSSL_SM4_CTR
16711
            case WC_SM4_CTR_TYPE:
16712
                WOLFSSL_MSG("SM4 CTR");
16713
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16714
                break;
16715
#endif
16716
#ifdef WOLFSSL_SM4_GCM
16717
            case WC_SM4_GCM_TYPE:
16718
                WOLFSSL_MSG("SM4 GCM");
16719
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16720
                break;
16721
#endif
16722
#ifdef WOLFSSL_SM4_CCM
16723
            case WC_SM4_CCM_TYPE:
16724
                WOLFSSL_MSG("SM4 CCM");
16725
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16726
                break;
16727
#endif
16728
16729
            case WC_NULL_CIPHER_TYPE :
16730
                WOLFSSL_MSG("NULL");
16731
                break;
16732
16733
            default: {
16734
                WOLFSSL_MSG("bad type");
16735
                return WOLFSSL_FATAL_ERROR;
16736
            }
16737
        }
16738
        return WOLFSSL_SUCCESS;
16739
    }
16740
16741
#ifndef NO_DES3
16742
16743
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
16744
                            unsigned char* iv, int len)
16745
{
16746
    (void)len;
16747
16748
    WOLFSSL_MSG("wolfSSL_3des_iv");
16749
16750
    if (ctx == NULL || iv == NULL) {
16751
        WOLFSSL_MSG("Bad function argument");
16752
        return;
16753
    }
16754
16755
    if (doset)
16756
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
16757
    else
16758
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
16759
}
16760
16761
#endif /* NO_DES3 */
16762
16763
16764
#ifndef NO_AES
16765
16766
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
16767
                      unsigned char* iv, int len)
16768
{
16769
    (void)len;
16770
16771
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
16772
16773
    if (ctx == NULL || iv == NULL) {
16774
        WOLFSSL_MSG("Bad function argument");
16775
        return;
16776
    }
16777
16778
    if (doset)
16779
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
16780
    else
16781
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
16782
}
16783
16784
#endif /* NO_AES */
16785
16786
#endif /* OPENSSL_EXTRA */
16787
16788
/*******************************************************************************
16789
 * END OF EVP_CIPHER API
16790
 ******************************************************************************/
16791
16792
#ifndef NO_CERTS
16793
16794
#define WOLFSSL_X509_STORE_INCLUDED
16795
#include <src/x509_str.c>
16796
16797
#define WOLFSSL_SSL_P7P12_INCLUDED
16798
#include <src/ssl_p7p12.c>
16799
16800
#endif /* !NO_CERTS */
16801
16802
16803
/*******************************************************************************
16804
 * BEGIN OPENSSL FIPS DRBG APIs
16805
 ******************************************************************************/
16806
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
16807
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
16808
{
16809
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16810
    if (ctx != NULL) {
16811
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
16812
        ctx->type = type;
16813
        ctx->xflags = (int)flags;
16814
        ctx->status = DRBG_STATUS_UNINITIALISED;
16815
        ret = WOLFSSL_SUCCESS;
16816
    }
16817
    return ret;
16818
}
16819
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
16820
{
16821
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16822
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
16823
        NULL, DYNAMIC_TYPE_OPENSSL);
16824
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
16825
    if (ret == WOLFSSL_SUCCESS && type != 0) {
16826
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
16827
    }
16828
    if (ret != WOLFSSL_SUCCESS) {
16829
        WOLFSSL_ERROR(ret);
16830
        wolfSSL_FIPS_drbg_free(ctx);
16831
        ctx = NULL;
16832
    }
16833
    return ctx;
16834
}
16835
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
16836
    const unsigned char* pers, size_t perslen)
16837
{
16838
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16839
    if (ctx != NULL && ctx->rng == NULL) {
16840
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16841
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
16842
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
16843
    #else
16844
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
16845
        if (ctx->rng != NULL) {
16846
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
16847
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
16848
        #else
16849
            ret = wc_InitRng(ctx->rng);
16850
            (void)pers;
16851
            (void)perslen;
16852
        #endif
16853
            if (ret != 0) {
16854
                WOLFSSL_ERROR(ret);
16855
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
16856
                ctx->rng = NULL;
16857
            }
16858
        }
16859
    #endif
16860
    }
16861
    if (ctx != NULL && ctx->rng != NULL) {
16862
        ctx->status = DRBG_STATUS_READY;
16863
        ret = WOLFSSL_SUCCESS;
16864
    }
16865
    return ret;
16866
}
16867
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
16868
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
16869
    size_t entropy_blocklen,
16870
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
16871
{
16872
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16873
    if (ctx != NULL) {
16874
        ctx->entropy_get = entropy_get;
16875
        ctx->entropy_clean = entropy_clean;
16876
        ctx->entropy_blocklen = entropy_blocklen;
16877
        ctx->none_get = none_get;
16878
        ctx->nonce_clean = nonce_clean;
16879
        ret = WOLFSSL_SUCCESS;
16880
    }
16881
    return ret;
16882
}
16883
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
16884
{
16885
    /* not implemented */
16886
    (void)buf;
16887
    (void)num;
16888
    (void)entropy;
16889
}
16890
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
16891
    size_t adinlen)
16892
{
16893
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16894
    if (ctx != NULL && ctx->rng != NULL) {
16895
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16896
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
16897
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
16898
            ret = WOLFSSL_SUCCESS;
16899
        }
16900
    #else
16901
        ret = WOLFSSL_SUCCESS;
16902
        (void)adin;
16903
        (void)adinlen;
16904
    #endif
16905
    }
16906
    return ret;
16907
}
16908
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
16909
    size_t outlen, int prediction_resistance, const unsigned char* adin,
16910
    size_t adinlen)
16911
{
16912
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16913
    if (ctx != NULL && ctx->rng != NULL) {
16914
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
16915
        if (ret == 0) {
16916
            ret = WOLFSSL_SUCCESS;
16917
        }
16918
    }
16919
    (void)prediction_resistance;
16920
    (void)adin;
16921
    (void)adinlen;
16922
    return ret;
16923
}
16924
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
16925
{
16926
    if (ctx != NULL && ctx->rng != NULL) {
16927
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16928
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
16929
        wc_rng_free(ctx->rng);
16930
    #else
16931
        wc_FreeRng(ctx->rng);
16932
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
16933
    #endif
16934
        ctx->rng = NULL;
16935
        ctx->status = DRBG_STATUS_UNINITIALISED;
16936
    }
16937
    return WOLFSSL_SUCCESS;
16938
}
16939
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
16940
{
16941
    if (ctx != NULL) {
16942
        /* As safety check if free'ing the default drbg, then mark global NULL.
16943
         * Technically the user should not call free on the default drbg. */
16944
        if (ctx == gDrbgDefCtx) {
16945
            gDrbgDefCtx = NULL;
16946
        }
16947
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
16948
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
16949
    }
16950
}
16951
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
16952
{
16953
    if (gDrbgDefCtx == NULL) {
16954
        gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
16955
    }
16956
    return gDrbgDefCtx;
16957
}
16958
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
16959
{
16960
    /* not implemented */
16961
    (void)buf;
16962
    (void)pctr;
16963
}
16964
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
16965
{
16966
    if (ctx != NULL) {
16967
        return ctx->app_data;
16968
    }
16969
    return NULL;
16970
}
16971
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
16972
{
16973
    if (ctx != NULL) {
16974
        ctx->app_data = app_data;
16975
    }
16976
}
16977
#endif
16978
/*******************************************************************************
16979
 * END OF OPENSSL FIPS DRBG APIs
16980
 ******************************************************************************/
16981
16982
16983
#endif /* !WOLFCRYPT_ONLY */