Coverage Report

Created: 2026-07-22 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-fastmath/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
1.29k
{
348
1.29k
    WC_RNG* ret = NULL;
349
350
1.29k
    if (initGlobalRNG == 0)
351
1.27k
        WOLFSSL_MSG("Global RNG no Init");
352
22
    else
353
22
        ret = &globalRNG;
354
355
1.29k
    return ret;
356
1.29k
}
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
263
{
400
263
    WC_RNG* ret = NULL;
401
263
#ifdef WOLFSSL_SMALL_STACK
402
263
    int freeRng = 0;
403
404
    /* Allocate RNG object . */
405
263
    if (rng == NULL) {
406
263
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
407
263
        freeRng = 1;
408
263
    }
409
263
#endif
410
411
263
    if (rng != NULL) {
412
263
        if (wc_InitRng(rng) == 0) {
413
263
            ret = rng;
414
263
            *local = 1;
415
263
        }
416
0
        else {
417
0
            WOLFSSL_MSG("Bad RNG Init");
418
0
#ifdef WOLFSSL_SMALL_STACK
419
0
            if (freeRng) {
420
0
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
421
0
                rng = NULL;
422
0
            }
423
0
#endif
424
0
        }
425
263
    }
426
263
    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
263
    return ret;
434
263
}
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
5.46k
{
549
5.46k
    WOLFSSL_CTX* ctx = NULL;
550
551
5.46k
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
552
553
5.46k
    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
5.46k
#ifndef NO_TLS
565
5.46k
    if (method == NULL)
566
0
        return ctx;
567
#else
568
    /* a blank TLS method */
569
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
570
#endif
571
572
5.46k
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
573
5.46k
    if (ctx) {
574
5.46k
        int ret;
575
576
5.46k
        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
5.46k
        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
5.46k
    }
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
5.46k
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
648
5.46k
    return ctx;
649
5.46k
}
650
651
652
WOLFSSL_ABI
653
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
654
5.51k
{
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
5.51k
    return wolfSSL_CTX_new_ex(method, NULL);
660
5.51k
#endif
661
5.51k
}
662
663
/* increases CTX reference count to track proper time to "free" */
664
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
665
91.3k
{
666
91.3k
    int ret;
667
91.3k
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
668
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
669
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
670
#else
671
91.3k
    (void)ret;
672
91.3k
    return WOLFSSL_SUCCESS;
673
91.3k
#endif
674
91.3k
}
675
676
WOLFSSL_ABI
677
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
678
5.46k
{
679
5.46k
    WOLFSSL_ENTER("wolfSSL_CTX_free");
680
5.46k
    if (ctx) {
681
5.46k
        FreeSSL_Ctx(ctx);
682
5.46k
    }
683
684
5.46k
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
685
5.46k
}
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
91.5k
{
754
91.5k
    WOLFSSL* ssl = NULL;
755
91.5k
    int ret = 0;
756
757
91.5k
    WOLFSSL_ENTER("wolfSSL_new");
758
759
91.5k
    if (ctx == NULL) {
760
0
        WOLFSSL_MSG("wolfSSL_new ctx is null");
761
0
        return NULL;
762
0
    }
763
764
91.5k
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
765
766
91.5k
    if (ssl == NULL) {
767
23
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
768
23
                        (int)sizeof(WOLFSSL));
769
23
    }
770
91.5k
    else {
771
91.5k
        ret = InitSSL(ssl, ctx, 0);
772
91.5k
        if (ret < 0) {
773
5.64k
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
774
5.64k
            FreeSSL(ssl, ctx->heap);
775
5.64k
            ssl = NULL;
776
5.64k
        }
777
85.9k
        else if (ret == 0) {
778
85.9k
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
779
85.9k
        }
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
91.5k
    } /* ssl XMALLOC success */
786
787
91.5k
    WOLFSSL_LEAVE("wolfSSL_new InitSSL =", ret);
788
91.5k
    (void)ret;
789
790
91.5k
    return ssl;
791
91.5k
}
792
793
794
WOLFSSL_ABI
795
void wolfSSL_free(WOLFSSL* ssl)
796
86.0k
{
797
86.0k
    WOLFSSL_ENTER("wolfSSL_free");
798
799
86.0k
    if (ssl) {
800
85.9k
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
801
85.9k
        FreeSSL(ssl, ssl->ctx->heap);
802
85.9k
    }
803
105
    else {
804
105
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
805
105
    }
806
86.0k
    WOLFSSL_LEAVE("wolfSSL_free", 0);
807
86.0k
}
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
68
{
1381
68
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
1382
1383
68
    WOLFSSL_ENTER("wolfSSL_negotiate");
1384
1385
68
    if (ssl == NULL)
1386
0
        return WOLFSSL_FATAL_ERROR;
1387
1388
68
#ifndef NO_WOLFSSL_SERVER
1389
68
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1390
68
#ifdef WOLFSSL_TLS13
1391
68
        if (IsAtLeastTLSv1_3(ssl->version))
1392
68
            err = wolfSSL_accept_TLSv13(ssl);
1393
0
        else
1394
0
#endif
1395
0
            err = wolfSSL_accept(ssl);
1396
68
    }
1397
68
#endif
1398
1399
68
#ifndef NO_WOLFSSL_CLIENT
1400
68
    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
68
#endif
1409
1410
68
    (void)ssl;
1411
1412
68
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
1413
1414
68
    return err;
1415
68
}
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
{
1637
    int ret = 0;
1638
1639
    WOLFSSL_ENTER("wolfSSL_write");
1640
1641
    if (ssl == NULL || data == NULL)
1642
        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
#ifdef HAVE_ERRNO_H
1793
    errno = 0;
1794
#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
    ret = SendData(ssl, data, sz);
1803
1804
    WOLFSSL_LEAVE("wolfSSL_write", ret);
1805
1806
    if (ret < 0)
1807
        return WOLFSSL_FATAL_ERROR;
1808
    else
1809
        return ret;
1810
}
1811
1812
WOLFSSL_ABI
1813
int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
1814
68
{
1815
68
    WOLFSSL_ENTER("wolfSSL_write");
1816
1817
68
    if (sz < 0)
1818
0
        return BAD_FUNC_ARG;
1819
1820
68
    return wolfSSL_write_internal(ssl, data, (size_t)sz);
1821
68
}
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
{
1898
    int ret;
1899
1900
    WOLFSSL_ENTER("wolfSSL_read_internal");
1901
1902
    if (ssl == NULL || data == NULL)
1903
        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
#ifdef HAVE_ERRNO_H
1944
        errno = 0;
1945
#endif
1946
1947
    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
    WOLFSSL_LEAVE("wolfSSL_read_internal", ret);
1968
1969
    if (ret < 0)
1970
        return WOLFSSL_FATAL_ERROR;
1971
    else
1972
        return ret;
1973
}
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
{
1990
    WOLFSSL_ENTER("wolfSSL_read");
1991
1992
    if (sz < 0)
1993
        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
    return wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
2005
}
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
40
{
2063
40
    int devId = INVALID_DEVID;
2064
40
    if (ssl != NULL)
2065
0
        devId = ssl->devId;
2066
40
    if (ctx != NULL && devId == INVALID_DEVID)
2067
40
        devId = ctx->devId;
2068
40
    return devId;
2069
40
}
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
919
{
2488
919
#ifndef WOLFSSL_AEAD_ONLY
2489
919
    if (ssl == NULL)
2490
0
        return NULL;
2491
2492
919
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
2493
141
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
2494
814
        return ssl->keys.client_write_MAC_secret;
2495
105
    else
2496
105
        return ssl->keys.server_write_MAC_secret;
2497
#else
2498
    (void)ssl;
2499
    (void)verify;
2500
2501
    return NULL;
2502
#endif
2503
919
}
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
5.46k
{
3164
5.46k
    int ret = WOLFSSL_SUCCESS;
3165
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
3166
    int i;
3167
#endif
3168
3169
5.46k
    WOLFSSL_ENTER("wolfSSL_Init");
3170
3171
5.46k
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
3172
5.46k
    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
5.46k
    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
5.46k
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
3226
        /* Initialize crypto for use with TLS connection */
3227
3228
5.46k
        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
5.46k
#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
5.46k
        if (ret == WOLFSSL_SUCCESS) {
3278
5.46k
            if (wc_InitRwLock(&session_lock) != 0) {
3279
0
                WOLFSSL_MSG("Bad Init Mutex session");
3280
0
                ret = BAD_MUTEX_E;
3281
0
            }
3282
5.46k
            else {
3283
5.46k
                session_lock_valid = 1;
3284
5.46k
            }
3285
5.46k
        }
3286
5.46k
    #endif
3287
5.46k
    #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
5.46k
    #endif
3300
5.46k
#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
5.46k
    }
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
5.46k
    if (ret == WOLFSSL_SUCCESS) {
3316
5.46k
        initRefCount = initRefCount + 1;
3317
5.46k
    }
3318
0
    else {
3319
0
        initRefCount = 1; /* Force cleanup */
3320
0
    }
3321
3322
5.46k
    wc_UnLockMutex(&inits_count_mutex);
3323
3324
5.46k
    if (ret != WOLFSSL_SUCCESS) {
3325
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
3326
0
    }
3327
3328
5.46k
    return ret;
3329
5.46k
}
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
        const char* keyLogFile = WOLFSSL_SSLKEYLOGFILE_OUTPUT;
3726
        FILE* f;
3727
    #ifdef WOLFSSL_SSLKEYLOGFILE_USE_ENV
3728
        /* RFC 9850: prefer the SSLKEYLOGFILE environment variable so other
3729
         * tools can share the path, else use the compile-time path. XGETENV is
3730
         * NULL where environment access is unavailable. Opt-in so a build with
3731
         * the variable exported for other applications is not affected. */
3732
        const char* keyLogEnv = XGETENV("SSLKEYLOGFILE");
3733
        if (keyLogEnv != NULL && keyLogEnv[0] != '\0')
3734
            keyLogFile = keyLogEnv;
3735
    #endif
3736
        f = XFOPEN(keyLogFile, "a");
3737
        if (f != XBADFILE) {
3738
            XFWRITE(pmsBuf, 1, pmsPos, f);
3739
            XFCLOSE(f);
3740
        }
3741
    }
3742
    #endif
3743
    return 0;
3744
}
3745
#endif /* SHOW_SECRETS */
3746
3747
#endif
3748
3749
3750
#ifdef OPENSSL_EXTRA
3751
3752
/*
3753
 * check if the list has TLS13 and pre-TLS13 suites
3754
 * @param list cipher suite list that user want to set
3755
 *         (caller required to check for NULL)
3756
 * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
3757
 */
3758
static int CheckcipherList(const char* list)
3759
{
3760
    int ret;
3761
    int findTLSv13Suites = 0;
3762
    int findbeforeSuites = 0;
3763
    byte cipherSuite0;
3764
    byte cipherSuite1;
3765
    int flags;
3766
    char* next = (char*)list;
3767
3768
    do {
3769
        char*  current = next;
3770
        char   name[MAX_SUITE_NAME + 1];
3771
        word32 length = MAX_SUITE_NAME;
3772
        word32 current_length;
3773
        byte major = INVALID_BYTE;
3774
        byte minor = INVALID_BYTE;
3775
3776
        next   = XSTRSTR(next, ":");
3777
3778
        if (next) {
3779
            current_length = (word32)(next - current);
3780
            ++next; /* increment to skip ':' */
3781
        }
3782
        else {
3783
            current_length = (word32)XSTRLEN(current);
3784
        }
3785
3786
        if (current_length == 0) {
3787
            break;
3788
        }
3789
3790
        if (current_length < length) {
3791
            length = current_length;
3792
        }
3793
        XMEMCPY(name, current, length);
3794
        name[length] = 0;
3795
3796
        if (XSTRCMP(name, "ALL") == 0 ||
3797
            XSTRCMP(name, "DEFAULT") == 0 ||
3798
            XSTRCMP(name, "HIGH") == 0)
3799
        {
3800
            findTLSv13Suites = 1;
3801
            findbeforeSuites = 1;
3802
            break;
3803
        }
3804
3805
        ret = GetCipherSuiteFromName(name, &cipherSuite0,
3806
                &cipherSuite1, &major, &minor, &flags);
3807
        if (ret == 0) {
3808
            if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) {
3809
                /* TLSv13 suite */
3810
                findTLSv13Suites = 1;
3811
            }
3812
            else {
3813
                findbeforeSuites = 1;
3814
            }
3815
        }
3816
3817
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
3818
        /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */
3819
        if (ret != 0) {
3820
            char* subStr = name;
3821
            char* subStrNext;
3822
3823
            do {
3824
                subStrNext = XSTRSTR(subStr, "+");
3825
3826
                if ((XSTRCMP(subStr, "ECDHE") == 0) ||
3827
                    (XSTRCMP(subStr, "RSA") == 0)) {
3828
                    return 0;
3829
                }
3830
3831
                if (subStrNext && (XSTRLEN(subStrNext) > 0)) {
3832
                    subStr = subStrNext + 1; /* +1 to skip past '+' */
3833
                }
3834
            } while (subStrNext != NULL);
3835
        }
3836
    #endif
3837
3838
        if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
3839
            /* list has mixed suites */
3840
            return 0;
3841
        }
3842
    } while (next);
3843
3844
    if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
3845
        ret = 1;/* only before TLSv13 suites */
3846
    }
3847
    else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
3848
        ret = 2;/* only TLSv13 suties */
3849
    }
3850
    else {
3851
        ret = 0;/* handle as mixed */
3852
    }
3853
    return ret;
3854
}
3855
3856
/* parse some bulk lists like !eNULL / !aNULL
3857
 *
3858
 * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
3859
 */
3860
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
3861
        Suites* suites, const char* list)
3862
{
3863
    int     ret = 0;
3864
    int     listattribute = 0;
3865
    int     tls13Only = 0;
3866
    WC_DECLARE_VAR(suitesCpy, byte, WOLFSSL_MAX_SUITE_SZ, 0);
3867
    word16  suitesCpySz = 0;
3868
    word16  i = 0;
3869
    word16  j = 0;
3870
3871
    if (suites == NULL || list == NULL) {
3872
        WOLFSSL_MSG("NULL argument");
3873
        return WOLFSSL_FAILURE;
3874
    }
3875
3876
    listattribute = CheckcipherList(list);
3877
3878
    if (listattribute == 0) {
3879
       /* list has mixed(pre-TLSv13 and TLSv13) suites
3880
        * update cipher suites the same as before
3881
        */
3882
        return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS :
3883
        WOLFSSL_FAILURE;
3884
    }
3885
    else if (listattribute == 1) {
3886
       /* list has only pre-TLSv13 suites.
3887
        * Only update before TLSv13 suites.
3888
        */
3889
        tls13Only = 0;
3890
    }
3891
    else if (listattribute == 2) {
3892
       /* list has only TLSv13 suites. Only update TLv13 suites
3893
        * simulate set_ciphersuites() compatibility layer API
3894
        */
3895
        tls13Only = 1;
3896
        if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) ||
3897
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) {
3898
            /* Silently ignore TLS 1.3 ciphers if we don't support it. */
3899
            return WOLFSSL_SUCCESS;
3900
        }
3901
    }
3902
3903
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
3904
#ifdef WOLFSSL_SMALL_STACK
3905
    if (suites->suiteSz > 0) {
3906
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
3907
                DYNAMIC_TYPE_TMP_BUFFER);
3908
        if (suitesCpy == NULL) {
3909
            return WOLFSSL_FAILURE;
3910
        }
3911
3912
        XMEMSET(suitesCpy, 0, suites->suiteSz);
3913
    }
3914
#else
3915
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
3916
#endif
3917
3918
    if (suites->suiteSz > 0)
3919
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
3920
    suitesCpySz = suites->suiteSz;
3921
3922
    ret = SetCipherList_ex(ctx, ssl, suites, list);
3923
    if (ret != 1) {
3924
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3925
        return WOLFSSL_FAILURE;
3926
    }
3927
3928
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
3929
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
3930
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
3931
     * Since we direct both API here we attempt to provide API compatibility. If
3932
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
3933
     * suites and keep the suites from the other group.
3934
     * If downgrade is disabled, skip preserving the other group's suites. */
3935
    if ((ssl != NULL && !ssl->options.downgrade) ||
3936
        (ctx != NULL && !ctx->method->downgrade)) {
3937
        /* Downgrade disabled - don't preserve other group's suites */
3938
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3939
        return ret;
3940
    }
3941
3942
    for (i = 0; i < suitesCpySz &&
3943
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
3944
        /* Check for duplicates */
3945
        int duplicate = 0;
3946
        for (j = 0; j < suites->suiteSz; j += 2) {
3947
            if (suitesCpy[i] == suites->suites[j] &&
3948
                    suitesCpy[i+1] == suites->suites[j+1]) {
3949
                duplicate = 1;
3950
                break;
3951
            }
3952
        }
3953
        if (!duplicate) {
3954
            if (tls13Only) {
3955
                /* Updating TLS 1.3 ciphers */
3956
                if (suitesCpy[i] != TLS13_BYTE) {
3957
                    /* Only copy over <= TLS 1.2 ciphers */
3958
                    /* TLS 1.3 ciphers take precedence */
3959
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
3960
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
3961
                }
3962
            }
3963
            else {
3964
                /* Updating <= TLS 1.2 ciphers */
3965
                if (suitesCpy[i] == TLS13_BYTE) {
3966
                    /* Only copy over TLS 1.3 ciphers */
3967
                    /* TLS 1.3 ciphers take precedence */
3968
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
3969
                             suites->suiteSz);
3970
                    suites->suites[0] = suitesCpy[i];
3971
                    suites->suites[1] = suitesCpy[i+1];
3972
                    suites->suiteSz += 2;
3973
                }
3974
            }
3975
        }
3976
    }
3977
3978
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3979
    return ret;
3980
}
3981
3982
#endif
3983
3984
3985
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
3986
0
{
3987
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
3988
3989
0
    if (ctx == NULL)
3990
0
        return WOLFSSL_FAILURE;
3991
3992
0
    if (AllocateCtxSuites(ctx) != 0)
3993
0
        return WOLFSSL_FAILURE;
3994
3995
#ifdef OPENSSL_EXTRA
3996
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
3997
#else
3998
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
3999
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
4000
0
#endif
4001
0
}
4002
4003
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
4004
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
4005
                                      const int listSz)
4006
{
4007
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
4008
4009
    if (ctx == NULL)
4010
        return WOLFSSL_FAILURE;
4011
4012
    if (AllocateCtxSuites(ctx) != 0)
4013
        return WOLFSSL_FAILURE;
4014
4015
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
4016
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
4017
}
4018
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
4019
4020
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
4021
0
{
4022
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
4023
4024
0
    if (ssl == NULL || ssl->ctx == NULL) {
4025
0
        return WOLFSSL_FAILURE;
4026
0
    }
4027
4028
0
    if (AllocateSuites(ssl) != 0)
4029
0
        return WOLFSSL_FAILURE;
4030
4031
#ifdef OPENSSL_EXTRA
4032
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
4033
#else
4034
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
4035
0
        WOLFSSL_SUCCESS :
4036
0
        WOLFSSL_FAILURE;
4037
0
#endif
4038
0
}
4039
4040
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
4041
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
4042
                                  const int listSz)
4043
{
4044
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
4045
4046
    if (ssl == NULL || ssl->ctx == NULL) {
4047
        return WOLFSSL_FAILURE;
4048
    }
4049
4050
    if (AllocateSuites(ssl) != 0)
4051
        return WOLFSSL_FAILURE;
4052
4053
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
4054
           ? WOLFSSL_SUCCESS
4055
           : WOLFSSL_FAILURE;
4056
}
4057
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
4058
4059
4060
#ifdef HAVE_KEYING_MATERIAL
4061
4062
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
4063
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
4064
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
4065
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
4066
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
4067
4068
static const struct ForbiddenLabels {
4069
    const char* label;
4070
    size_t labelLen;
4071
} forbiddenLabels[] = {
4072
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
4073
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
4074
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
4075
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
4076
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
4077
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
4078
    {NULL, 0},
4079
};
4080
4081
/**
4082
 * Implement RFC 5705
4083
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
4084
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
4085
 */
4086
int wolfSSL_export_keying_material(WOLFSSL *ssl,
4087
        unsigned char *out, size_t outLen,
4088
        const char *label, size_t labelLen,
4089
        const unsigned char *context, size_t contextLen,
4090
        int use_context)
4091
{
4092
    byte*  seed = NULL;
4093
    word32 seedLen;
4094
    const struct ForbiddenLabels* fl;
4095
4096
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
4097
4098
    if (ssl == NULL || out == NULL || label == NULL ||
4099
            (use_context && contextLen && context == NULL)) {
4100
        WOLFSSL_MSG("Bad argument");
4101
        return WOLFSSL_FAILURE;
4102
    }
4103
4104
    /* Sanity check contextLen to prevent integer overflow when cast to word32
4105
     * and to ensure it fits in the 2-byte length encoding (max 65535). */
4106
    if (use_context && contextLen > WOLFSSL_MAX_16BIT) {
4107
        WOLFSSL_MSG("contextLen too large");
4108
        return WOLFSSL_FAILURE;
4109
    }
4110
4111
    /* clientRandom + serverRandom
4112
     * OR
4113
     * clientRandom + serverRandom + ctx len encoding + ctx */
4114
    seedLen = !use_context ? (word32)SEED_LEN :
4115
                             (word32)SEED_LEN + 2 + (word32)contextLen;
4116
4117
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
4118
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
4119
                    "data. Call wolfSSL_KeepArrays before attempting to "
4120
                    "export keyid material.");
4121
        return WOLFSSL_FAILURE;
4122
    }
4123
4124
    /* check forbidden labels */
4125
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
4126
        if (labelLen >= fl->labelLen &&
4127
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
4128
            WOLFSSL_MSG("Forbidden label");
4129
            return WOLFSSL_FAILURE;
4130
        }
4131
    }
4132
4133
#ifdef WOLFSSL_TLS13
4134
    if (IsAtLeastTLSv1_3(ssl->version)) {
4135
        /* Path for TLS 1.3 */
4136
        if (!use_context) {
4137
            contextLen = 0;
4138
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
4139
        }
4140
4141
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
4142
                context, contextLen) != 0) {
4143
            WOLFSSL_MSG("Tls13_Exporter error");
4144
            return WOLFSSL_FAILURE;
4145
        }
4146
        return WOLFSSL_SUCCESS;
4147
    }
4148
#endif
4149
4150
    /* Path for <=TLS 1.2 */
4151
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4152
    if (seed == NULL) {
4153
        WOLFSSL_MSG("malloc error");
4154
        return WOLFSSL_FAILURE;
4155
    }
4156
4157
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
4158
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
4159
4160
    if (use_context) {
4161
        /* Encode len in big endian */
4162
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
4163
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
4164
        if (contextLen) {
4165
            /* 0 length context is allowed */
4166
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
4167
        }
4168
    }
4169
4170
    PRIVATE_KEY_UNLOCK();
4171
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
4172
            (byte*)label, (word32)labelLen, seed, seedLen,
4173
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
4174
            ssl->devId) != 0) {
4175
        WOLFSSL_MSG("wc_PRF_TLS error");
4176
        PRIVATE_KEY_LOCK();
4177
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4178
        return WOLFSSL_FAILURE;
4179
    }
4180
    PRIVATE_KEY_LOCK();
4181
4182
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4183
    return WOLFSSL_SUCCESS;
4184
}
4185
#endif /* HAVE_KEYING_MATERIAL */
4186
4187
4188
/* EITHER SIDE METHODS */
4189
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
4190
    WOLFSSL_METHOD* wolfSSLv23_method(void)
4191
    {
4192
        return wolfSSLv23_method_ex(NULL);
4193
    }
4194
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
4195
    {
4196
        WOLFSSL_METHOD* m = NULL;
4197
        WOLFSSL_ENTER("wolfSSLv23_method");
4198
    #if !defined(NO_WOLFSSL_CLIENT)
4199
        m = wolfSSLv23_client_method_ex(heap);
4200
    #elif !defined(NO_WOLFSSL_SERVER)
4201
        m = wolfSSLv23_server_method_ex(heap);
4202
    #else
4203
        (void)heap;
4204
    #endif
4205
        if (m != NULL) {
4206
            m->side = WOLFSSL_NEITHER_END;
4207
        }
4208
4209
        return m;
4210
    }
4211
4212
    #ifndef NO_OLD_TLS
4213
    #ifdef WOLFSSL_ALLOW_SSLV3
4214
    WOLFSSL_METHOD* wolfSSLv3_method(void)
4215
    {
4216
        return wolfSSLv3_method_ex(NULL);
4217
    }
4218
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
4219
    {
4220
        WOLFSSL_METHOD* m = NULL;
4221
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
4222
    #if !defined(NO_WOLFSSL_CLIENT)
4223
        m = wolfSSLv3_client_method_ex(heap);
4224
    #elif !defined(NO_WOLFSSL_SERVER)
4225
        m = wolfSSLv3_server_method_ex(heap);
4226
    #endif
4227
        if (m != NULL) {
4228
            m->side = WOLFSSL_NEITHER_END;
4229
        }
4230
4231
        return m;
4232
    }
4233
    #endif
4234
    #endif
4235
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
4236
4237
/* client only parts */
4238
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
4239
4240
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
4241
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
4242
    {
4243
        WOLFSSL_STUB("wolfSSLv2_client_method");
4244
        return NULL;
4245
    }
4246
    #endif
4247
4248
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4249
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
4250
    {
4251
        return wolfSSLv3_client_method_ex(NULL);
4252
    }
4253
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
4254
    {
4255
        WOLFSSL_METHOD* method =
4256
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4257
                                                     heap, DYNAMIC_TYPE_METHOD);
4258
        (void)heap;
4259
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
4260
        if (method)
4261
            InitSSL_Method(method, MakeSSLv3());
4262
        return method;
4263
    }
4264
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
4265
4266
4267
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
4268
0
    {
4269
0
        return wolfSSLv23_client_method_ex(NULL);
4270
0
    }
4271
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
4272
0
    {
4273
0
        WOLFSSL_METHOD* method =
4274
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4275
0
                                                     heap, DYNAMIC_TYPE_METHOD);
4276
0
        (void)heap;
4277
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
4278
0
        if (method) {
4279
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
4280
0
        defined(WOLFSSL_SHA512)
4281
0
        #if defined(WOLFSSL_TLS13)
4282
0
            InitSSL_Method(method, MakeTLSv1_3());
4283
        #elif !defined(WOLFSSL_NO_TLS12)
4284
            InitSSL_Method(method, MakeTLSv1_2());
4285
        #elif !defined(NO_OLD_TLS)
4286
            InitSSL_Method(method, MakeTLSv1_1());
4287
        #endif
4288
    #else
4289
        #ifndef NO_OLD_TLS
4290
            InitSSL_Method(method, MakeTLSv1_1());
4291
        #endif
4292
    #endif
4293
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
4294
0
            method->downgrade = 1;
4295
0
    #endif
4296
0
        }
4297
0
        return method;
4298
0
    }
4299
4300
    /* please see note at top of README if you get an error from connect */
4301
    WOLFSSL_ABI
4302
    int wolfSSL_connect(WOLFSSL* ssl)
4303
    {
4304
    #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4305
          defined(WOLFSSL_TLS13))
4306
        int neededState;
4307
        byte advanceState;
4308
    #endif
4309
        int ret = 0;
4310
4311
        (void)ret;
4312
4313
        #ifdef HAVE_ERRNO_H
4314
            errno = 0;
4315
        #endif
4316
4317
        if (ssl == NULL)
4318
            return BAD_FUNC_ARG;
4319
4320
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
4321
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
4322
            ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
4323
            if (ssl->error != WOLFSSL_SUCCESS) {
4324
                WOLFSSL_ERROR(ssl->error);
4325
                return WOLFSSL_FATAL_ERROR;
4326
            }
4327
            ssl->error = 0; /* expected to be zero here */
4328
        }
4329
4330
    #ifdef OPENSSL_EXTRA
4331
        if (ssl->CBIS != NULL) {
4332
            ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS);
4333
            ssl->cbmode = WOLFSSL_CB_WRITE;
4334
        }
4335
    #endif
4336
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
4337
4338
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4339
        defined(WOLFSSL_TLS13)
4340
        return wolfSSL_connect_TLSv13(ssl);
4341
    #else
4342
        #ifdef WOLFSSL_TLS13
4343
        if (ssl->options.tls1_3) {
4344
            WOLFSSL_MSG("TLS 1.3");
4345
            return wolfSSL_connect_TLSv13(ssl);
4346
        }
4347
        #endif
4348
4349
        WOLFSSL_MSG("TLS 1.2 or lower");
4350
        WOLFSSL_ENTER("wolfSSL_connect");
4351
4352
        /* make sure this wolfSSL object has arrays and rng setup. Protects
4353
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
4354
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
4355
            return ret;
4356
        }
4357
4358
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
4359
        if ((ssl->ConnectFilter != NULL) &&
4360
            (ssl->options.connectState == CONNECT_BEGIN)) {
4361
            wolfSSL_netfilter_decision_t res;
4362
            if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
4363
                 WOLFSSL_SUCCESS) &&
4364
                (res == WOLFSSL_NETFILTER_REJECT)) {
4365
                ssl->error = SOCKET_FILTERED_E;
4366
                WOLFSSL_ERROR(ssl->error);
4367
                return WOLFSSL_FATAL_ERROR;
4368
            }
4369
        }
4370
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
4371
4372
        if (ssl->options.side != WOLFSSL_CLIENT_END) {
4373
            ssl->error = SIDE_ERROR;
4374
            WOLFSSL_ERROR(ssl->error);
4375
            return WOLFSSL_FATAL_ERROR;
4376
        }
4377
4378
        #ifdef WOLFSSL_DTLS
4379
        if (ssl->version.major == DTLS_MAJOR) {
4380
            ssl->options.dtls   = 1;
4381
            ssl->options.tls    = 1;
4382
            ssl->options.tls1_1 = 1;
4383
            ssl->options.dtlsStateful = 1;
4384
        }
4385
        #endif
4386
4387
        /* fragOffset is non-zero when sending fragments. On the last
4388
         * fragment, fragOffset is zero again, and the state can be
4389
         * advanced. */
4390
        advanceState = ssl->fragOffset == 0 &&
4391
            (ssl->options.connectState == CONNECT_BEGIN ||
4392
             ssl->options.connectState == HELLO_AGAIN ||
4393
             (ssl->options.connectState >= FIRST_REPLY_DONE &&
4394
              ssl->options.connectState <= FIRST_REPLY_FOURTH));
4395
4396
#ifdef WOLFSSL_DTLS13
4397
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
4398
            advanceState = advanceState && !ssl->dtls13SendingAckOrRtx;
4399
#endif /* WOLFSSL_DTLS13 */
4400
4401
        if (ssl->buffers.outputBuffer.length > 0
4402
        #ifdef WOLFSSL_ASYNC_CRYPT
4403
            /* do not send buffered or advance state if last error was an
4404
                async pending operation */
4405
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
4406
        #endif
4407
        ) {
4408
            ret = SendBuffered(ssl);
4409
            if (ret == 0) {
4410
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
4411
                    if (advanceState) {
4412
                        ssl->options.connectState++;
4413
                        WOLFSSL_MSG("connect state: Advanced from last "
4414
                                    "buffered fragment send");
4415
                    #ifdef WOLFSSL_ASYNC_IO
4416
                        /* Cleanup async */
4417
                        FreeAsyncCtx(ssl, 0);
4418
                    #endif
4419
                    }
4420
                }
4421
                else {
4422
                    WOLFSSL_MSG("connect state: "
4423
                                "Not advanced, more fragments to send");
4424
                }
4425
            }
4426
            else {
4427
                ssl->error = ret;
4428
                WOLFSSL_ERROR(ssl->error);
4429
                return WOLFSSL_FATAL_ERROR;
4430
            }
4431
#ifdef WOLFSSL_DTLS13
4432
            if (ssl->options.dtls)
4433
                ssl->dtls13SendingAckOrRtx = 0;
4434
#endif /* WOLFSSL_DTLS13 */
4435
        }
4436
4437
        ret = RetrySendAlert(ssl);
4438
        if (ret != 0) {
4439
            ssl->error = ret;
4440
            WOLFSSL_ERROR(ssl->error);
4441
            return WOLFSSL_FATAL_ERROR;
4442
        }
4443
4444
        switch (ssl->options.connectState) {
4445
4446
        case CONNECT_BEGIN :
4447
            /* always send client hello first */
4448
            if ( (ssl->error = SendClientHello(ssl)) != 0) {
4449
                WOLFSSL_ERROR(ssl->error);
4450
                return WOLFSSL_FATAL_ERROR;
4451
            }
4452
            ssl->options.connectState = CLIENT_HELLO_SENT;
4453
            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
4454
            FALL_THROUGH;
4455
4456
        case CLIENT_HELLO_SENT :
4457
            neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
4458
                                          SERVER_HELLODONE_COMPLETE;
4459
            #ifdef WOLFSSL_DTLS
4460
                /* In DTLS, when resuming, we can go straight to FINISHED,
4461
                 * or do a cookie exchange and then skip to FINISHED, assume
4462
                 * we need the cookie exchange first. */
4463
                if (IsDtlsNotSctpMode(ssl))
4464
                    neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
4465
            #endif
4466
            /* get response */
4467
            WOLFSSL_MSG("Server state up to needed state.");
4468
            while (ssl->options.serverState < neededState) {
4469
                WOLFSSL_MSG("Progressing server state...");
4470
                #ifdef WOLFSSL_TLS13
4471
                    if (ssl->options.tls1_3)
4472
                        return wolfSSL_connect_TLSv13(ssl);
4473
                #endif
4474
                WOLFSSL_MSG("ProcessReply...");
4475
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
4476
                    WOLFSSL_ERROR(ssl->error);
4477
                    return WOLFSSL_FATAL_ERROR;
4478
                }
4479
                /* if resumption failed, reset needed state */
4480
                else if (neededState == SERVER_FINISHED_COMPLETE) {
4481
                    if (!ssl->options.resuming) {
4482
                    #ifdef WOLFSSL_DTLS
4483
                        if (IsDtlsNotSctpMode(ssl))
4484
                            neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
4485
                        else
4486
                    #endif
4487
                            neededState = SERVER_HELLODONE_COMPLETE;
4488
                    }
4489
                }
4490
                WOLFSSL_MSG("ProcessReply done.");
4491
4492
#ifdef WOLFSSL_DTLS13
4493
                if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)
4494
                    && ssl->dtls13Rtx.sendAcks == 1
4495
                    && ssl->options.seenUnifiedHdr) {
4496
                    /* we aren't negotiated the version yet, so we aren't sure
4497
                     * the other end can speak v1.3. On the other side we have
4498
                     * received a unified records, assuming that the
4499
                     * ServerHello got lost, we will send an empty ACK. In case
4500
                     * the server is a DTLS with version less than 1.3, it
4501
                     * should just ignore the message */
4502
                    ssl->dtls13Rtx.sendAcks = 0;
4503
                    if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
4504
                        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4505
                            ssl->dtls13SendingAckOrRtx = 1;
4506
                        WOLFSSL_ERROR(ssl->error);
4507
                        return WOLFSSL_FATAL_ERROR;
4508
                    }
4509
                }
4510
#endif /* WOLFSSL_DTLS13 */
4511
            }
4512
4513
            ssl->options.connectState = HELLO_AGAIN;
4514
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
4515
            FALL_THROUGH;
4516
4517
        case HELLO_AGAIN :
4518
4519
        #ifdef WOLFSSL_TLS13
4520
            if (ssl->options.tls1_3)
4521
                return wolfSSL_connect_TLSv13(ssl);
4522
        #endif
4523
4524
            #ifdef WOLFSSL_DTLS
4525
            if (ssl->options.serverState ==
4526
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
4527
                if (IsDtlsNotSctpMode(ssl)) {
4528
                    /* re-init hashes, exclude first hello and verify request */
4529
                    if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
4530
                        WOLFSSL_ERROR(ssl->error);
4531
                        return WOLFSSL_FATAL_ERROR;
4532
                    }
4533
                    if ( (ssl->error = SendClientHello(ssl)) != 0) {
4534
                        WOLFSSL_ERROR(ssl->error);
4535
                        return WOLFSSL_FATAL_ERROR;
4536
                    }
4537
                }
4538
            }
4539
            #endif
4540
4541
            ssl->options.connectState = HELLO_AGAIN_REPLY;
4542
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
4543
            FALL_THROUGH;
4544
4545
        case HELLO_AGAIN_REPLY :
4546
            #ifdef WOLFSSL_DTLS
4547
                if (IsDtlsNotSctpMode(ssl)) {
4548
                    neededState = ssl->options.resuming ?
4549
                           SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
4550
4551
                    /* get response */
4552
                    while (ssl->options.serverState < neededState) {
4553
                        if ( (ssl->error = ProcessReply(ssl)) < 0) {
4554
                            WOLFSSL_ERROR(ssl->error);
4555
                            return WOLFSSL_FATAL_ERROR;
4556
                        }
4557
                        /* if resumption failed, reset needed state */
4558
                        if (neededState == SERVER_FINISHED_COMPLETE) {
4559
                            if (!ssl->options.resuming)
4560
                                neededState = SERVER_HELLODONE_COMPLETE;
4561
                        }
4562
                    }
4563
                }
4564
            #endif
4565
4566
            ssl->options.connectState = FIRST_REPLY_DONE;
4567
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
4568
            FALL_THROUGH;
4569
4570
        case FIRST_REPLY_DONE :
4571
            if (ssl->options.certOnly)
4572
                return WOLFSSL_SUCCESS;
4573
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
4574
                #ifdef WOLFSSL_TLS13
4575
                    if (ssl->options.tls1_3)
4576
                        return wolfSSL_connect_TLSv13(ssl);
4577
                #endif
4578
                if (ssl->options.sendVerify) {
4579
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
4580
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4581
                        WOLFSSL_ERROR(ssl->error);
4582
                        return WOLFSSL_FATAL_ERROR;
4583
                    }
4584
                    WOLFSSL_MSG("sent: certificate");
4585
                }
4586
4587
            #endif
4588
            ssl->options.connectState = FIRST_REPLY_FIRST;
4589
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
4590
            FALL_THROUGH;
4591
4592
        case FIRST_REPLY_FIRST :
4593
        #ifdef WOLFSSL_TLS13
4594
            if (ssl->options.tls1_3)
4595
                return wolfSSL_connect_TLSv13(ssl);
4596
        #endif
4597
            if (!ssl->options.resuming) {
4598
                if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
4599
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4600
#ifdef WOLFSSL_EXTRA_ALERTS
4601
                    if (ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY) ||
4602
                        ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) {
4603
                        SendAlert(ssl, alert_fatal, handshake_failure);
4604
                    }
4605
#endif
4606
                    WOLFSSL_ERROR(ssl->error);
4607
                    return WOLFSSL_FATAL_ERROR;
4608
                }
4609
                WOLFSSL_MSG("sent: client key exchange");
4610
            }
4611
4612
            ssl->options.connectState = FIRST_REPLY_SECOND;
4613
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
4614
            FALL_THROUGH;
4615
4616
    #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
4617
        case FIRST_REPLY_SECOND :
4618
            /* CLIENT: Fail-safe for Server Authentication. */
4619
            if (!ssl->options.peerAuthGood) {
4620
                WOLFSSL_MSG("Server authentication did not happen");
4621
                ssl->error = NO_PEER_VERIFY;
4622
                return WOLFSSL_FATAL_ERROR;
4623
            }
4624
4625
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
4626
                if (ssl->options.sendVerify) {
4627
                    if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
4628
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4629
                        WOLFSSL_ERROR(ssl->error);
4630
                        return WOLFSSL_FATAL_ERROR;
4631
                    }
4632
                    WOLFSSL_MSG("sent: certificate verify");
4633
                }
4634
            #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
4635
            ssl->options.connectState = FIRST_REPLY_THIRD;
4636
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
4637
            FALL_THROUGH;
4638
4639
        case FIRST_REPLY_THIRD :
4640
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
4641
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4642
                WOLFSSL_ERROR(ssl->error);
4643
                return WOLFSSL_FATAL_ERROR;
4644
            }
4645
            WOLFSSL_MSG("sent: change cipher spec");
4646
            ssl->options.connectState = FIRST_REPLY_FOURTH;
4647
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
4648
            FALL_THROUGH;
4649
4650
        case FIRST_REPLY_FOURTH :
4651
            if ( (ssl->error = SendFinished(ssl)) != 0) {
4652
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
4653
                WOLFSSL_ERROR(ssl->error);
4654
                return WOLFSSL_FATAL_ERROR;
4655
            }
4656
            WOLFSSL_MSG("sent: finished");
4657
            ssl->options.connectState = FINISHED_DONE;
4658
            WOLFSSL_MSG("connect state: FINISHED_DONE");
4659
            FALL_THROUGH;
4660
4661
#ifdef WOLFSSL_DTLS13
4662
        case WAIT_FINISHED_ACK:
4663
            ssl->options.connectState = FINISHED_DONE;
4664
            FALL_THROUGH;
4665
#endif /* WOLFSSL_DTLS13 */
4666
4667
        case FINISHED_DONE :
4668
            /* get response */
4669
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
4670
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
4671
                    WOLFSSL_ERROR(ssl->error);
4672
                    return WOLFSSL_FATAL_ERROR;
4673
                }
4674
4675
            ssl->options.connectState = SECOND_REPLY_DONE;
4676
            WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
4677
            FALL_THROUGH;
4678
4679
        case SECOND_REPLY_DONE:
4680
        #ifndef NO_HANDSHAKE_DONE_CB
4681
            if (ssl->hsDoneCb) {
4682
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
4683
                if (cbret < 0) {
4684
                    ssl->error = cbret;
4685
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
4686
                    return WOLFSSL_FATAL_ERROR;
4687
                }
4688
            }
4689
        #endif /* NO_HANDSHAKE_DONE_CB */
4690
4691
            if (!ssl->options.dtls) {
4692
                if (!ssl->options.keepResources) {
4693
                    FreeHandshakeResources(ssl);
4694
                }
4695
            }
4696
        #ifdef WOLFSSL_DTLS
4697
            else {
4698
                ssl->options.dtlsHsRetain = 1;
4699
            }
4700
        #endif /* WOLFSSL_DTLS */
4701
4702
        #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
4703
            /* This may be necessary in async so that we don't try to
4704
             * renegotiate again */
4705
            if (ssl->secure_renegotiation &&
4706
                    ssl->secure_renegotiation->startScr) {
4707
                ssl->secure_renegotiation->startScr = 0;
4708
            }
4709
        #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
4710
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
4711
            /* Free the remaining async context if not using it for crypto */
4712
            FreeAsyncCtx(ssl, 1);
4713
        #endif
4714
4715
            ssl->error = 0; /* clear the error */
4716
4717
            WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
4718
            return WOLFSSL_SUCCESS;
4719
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
4720
4721
        default:
4722
            WOLFSSL_MSG("Unknown connect state ERROR");
4723
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
4724
        }
4725
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
4726
    }
4727
4728
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
4729
/* end client only parts */
4730
4731
/* server only parts */
4732
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
4733
4734
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
4735
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
4736
    {
4737
        WOLFSSL_STUB("wolfSSLv2_server_method");
4738
        return 0;
4739
    }
4740
    #endif
4741
4742
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4743
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
4744
    {
4745
        return wolfSSLv3_server_method_ex(NULL);
4746
    }
4747
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
4748
    {
4749
        WOLFSSL_METHOD* method =
4750
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4751
                                                     heap, DYNAMIC_TYPE_METHOD);
4752
        (void)heap;
4753
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
4754
        if (method) {
4755
            InitSSL_Method(method, MakeSSLv3());
4756
            method->side = WOLFSSL_SERVER_END;
4757
        }
4758
        return method;
4759
    }
4760
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
4761
4762
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
4763
0
    {
4764
0
        return wolfSSLv23_server_method_ex(NULL);
4765
0
    }
4766
4767
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
4768
0
    {
4769
0
        WOLFSSL_METHOD* method =
4770
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
4771
0
                                                     heap, DYNAMIC_TYPE_METHOD);
4772
0
        (void)heap;
4773
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
4774
0
        if (method) {
4775
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
4776
0
        defined(WOLFSSL_SHA512)
4777
0
        #ifdef WOLFSSL_TLS13
4778
0
            InitSSL_Method(method, MakeTLSv1_3());
4779
        #elif !defined(WOLFSSL_NO_TLS12)
4780
            InitSSL_Method(method, MakeTLSv1_2());
4781
        #elif !defined(NO_OLD_TLS)
4782
            InitSSL_Method(method, MakeTLSv1_1());
4783
        #endif
4784
    #else
4785
        #ifndef NO_OLD_TLS
4786
            InitSSL_Method(method, MakeTLSv1_1());
4787
        #else
4788
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
4789
        #endif
4790
    #endif
4791
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
4792
0
            method->downgrade = 1;
4793
0
    #endif
4794
0
            method->side      = WOLFSSL_SERVER_END;
4795
0
        }
4796
0
        return method;
4797
0
    }
4798
4799
4800
    WOLFSSL_ABI
4801
    int wolfSSL_accept(WOLFSSL* ssl)
4802
    {
4803
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
4804
    defined(WOLFSSL_TLS13))
4805
        word16 havePSK = 0;
4806
        word16 haveAnon = 0;
4807
        word16 haveMcast = 0;
4808
#endif
4809
        int ret = 0;
4810
4811
        (void)ret;
4812
4813
        if (ssl == NULL)
4814
            return WOLFSSL_FATAL_ERROR;
4815
4816
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
4817
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
4818
            WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
4819
            ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
4820
            if (ssl->error != WOLFSSL_SUCCESS) {
4821
                WOLFSSL_ERROR(ssl->error);
4822
                return WOLFSSL_FATAL_ERROR;
4823
            }
4824
            ssl->error = 0; /* expected to be zero here */
4825
        }
4826
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
4827
4828
#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
4829
        return wolfSSL_accept_TLSv13(ssl);
4830
#else
4831
    #ifdef WOLFSSL_TLS13
4832
        if (ssl->options.tls1_3)
4833
            return wolfSSL_accept_TLSv13(ssl);
4834
    #endif
4835
        WOLFSSL_ENTER("wolfSSL_accept");
4836
4837
        /* make sure this wolfSSL object has arrays and rng setup. Protects
4838
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
4839
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
4840
            return ret;
4841
        }
4842
4843
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
4844
        if ((ssl->AcceptFilter != NULL) &&
4845
            ((ssl->options.acceptState == ACCEPT_BEGIN)
4846
#ifdef HAVE_SECURE_RENEGOTIATION
4847
             || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
4848
#endif
4849
                ))
4850
        {
4851
            wolfSSL_netfilter_decision_t res;
4852
            if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
4853
                 WOLFSSL_SUCCESS) &&
4854
                (res == WOLFSSL_NETFILTER_REJECT)) {
4855
                ssl->error = SOCKET_FILTERED_E;
4856
                WOLFSSL_ERROR(ssl->error);
4857
                return WOLFSSL_FATAL_ERROR;
4858
            }
4859
        }
4860
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
4861
4862
        #ifdef HAVE_ERRNO_H
4863
            errno = 0;
4864
        #endif
4865
4866
        #ifndef NO_PSK
4867
            havePSK = ssl->options.havePSK;
4868
        #endif
4869
        (void)havePSK;
4870
4871
        #ifdef HAVE_ANON
4872
            haveAnon = ssl->options.useAnon;
4873
        #endif
4874
        (void)haveAnon;
4875
4876
        #ifdef WOLFSSL_MULTICAST
4877
            haveMcast = ssl->options.haveMcast;
4878
        #endif
4879
        (void)haveMcast;
4880
4881
        if (ssl->options.side != WOLFSSL_SERVER_END) {
4882
            ssl->error = SIDE_ERROR;
4883
            WOLFSSL_ERROR(ssl->error);
4884
            return WOLFSSL_FATAL_ERROR;
4885
        }
4886
4887
    #ifndef NO_CERTS
4888
        /* in case used set_accept_state after init */
4889
        if (!havePSK && !haveAnon && !haveMcast) {
4890
        #ifdef WOLFSSL_CERT_SETUP_CB
4891
            if (ssl->ctx->certSetupCb != NULL) {
4892
                WOLFSSL_MSG("CertSetupCb set. server cert and "
4893
                            "key not checked");
4894
            }
4895
            else
4896
        #endif
4897
            {
4898
                if (!ssl->buffers.certificate ||
4899
                    !ssl->buffers.certificate->buffer) {
4900
4901
                    WOLFSSL_MSG("accept error: server cert required");
4902
                    ssl->error = NO_PRIVATE_KEY;
4903
                    WOLFSSL_ERROR(ssl->error);
4904
                    return WOLFSSL_FATAL_ERROR;
4905
                }
4906
4907
                if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
4908
                    /* allow no private key if using existing key */
4909
                #ifdef WOLF_PRIVATE_KEY_ID
4910
                    if (ssl->devId != INVALID_DEVID
4911
                    #ifdef HAVE_PK_CALLBACKS
4912
                        || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
4913
                    #endif
4914
                    ) {
4915
                        WOLFSSL_MSG("Allowing no server private key "
4916
                                    "(external)");
4917
                    }
4918
                    else
4919
                #endif
4920
                    {
4921
                        WOLFSSL_MSG("accept error: server key required");
4922
                        ssl->error = NO_PRIVATE_KEY;
4923
                        WOLFSSL_ERROR(ssl->error);
4924
                        return WOLFSSL_FATAL_ERROR;
4925
                    }
4926
                }
4927
            }
4928
        }
4929
    #endif
4930
4931
    #ifdef WOLFSSL_DTLS
4932
        if (ssl->version.major == DTLS_MAJOR) {
4933
            ssl->options.dtls   = 1;
4934
            ssl->options.tls    = 1;
4935
            ssl->options.tls1_1 = 1;
4936
            if (!IsDtlsNotSctpMode(ssl) || IsSCR(ssl))
4937
                ssl->options.dtlsStateful = 1;
4938
        }
4939
    #endif
4940
4941
        if (ssl->buffers.outputBuffer.length > 0
4942
        #ifdef WOLFSSL_ASYNC_CRYPT
4943
            /* do not send buffered or advance state if last error was an
4944
                async pending operation */
4945
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
4946
        #endif
4947
        ) {
4948
            ret = SendBuffered(ssl);
4949
            if (ret == 0) {
4950
                /* fragOffset is non-zero when sending fragments. On the last
4951
                 * fragment, fragOffset is zero again, and the state can be
4952
                 * advanced. */
4953
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
4954
                    if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE ||
4955
                        ssl->options.acceptState == SERVER_HELLO_SENT ||
4956
                        ssl->options.acceptState == CERT_SENT ||
4957
                        ssl->options.acceptState == CERT_STATUS_SENT ||
4958
                        ssl->options.acceptState == KEY_EXCHANGE_SENT ||
4959
                        ssl->options.acceptState == CERT_REQ_SENT ||
4960
                        ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE ||
4961
                        ssl->options.acceptState == TICKET_SENT ||
4962
                        ssl->options.acceptState == CHANGE_CIPHER_SENT) {
4963
                        ssl->options.acceptState++;
4964
                        WOLFSSL_MSG("accept state: Advanced from last "
4965
                                    "buffered fragment send");
4966
                    #ifdef WOLFSSL_ASYNC_IO
4967
                        /* Cleanup async */
4968
                        FreeAsyncCtx(ssl, 0);
4969
                    #endif
4970
                    }
4971
                }
4972
                else {
4973
                    WOLFSSL_MSG("accept state: "
4974
                                "Not advanced, more fragments to send");
4975
                }
4976
            }
4977
            else {
4978
                ssl->error = ret;
4979
                WOLFSSL_ERROR(ssl->error);
4980
                return WOLFSSL_FATAL_ERROR;
4981
            }
4982
#ifdef WOLFSSL_DTLS13
4983
            if (ssl->options.dtls)
4984
                ssl->dtls13SendingAckOrRtx = 0;
4985
#endif /* WOLFSSL_DTLS13 */
4986
        }
4987
4988
        ret = RetrySendAlert(ssl);
4989
        if (ret != 0) {
4990
            ssl->error = ret;
4991
            WOLFSSL_ERROR(ssl->error);
4992
            return WOLFSSL_FATAL_ERROR;
4993
        }
4994
4995
        switch (ssl->options.acceptState) {
4996
4997
        case ACCEPT_BEGIN :
4998
#ifdef HAVE_SECURE_RENEGOTIATION
4999
        case ACCEPT_BEGIN_RENEG:
5000
#endif
5001
            /* get response */
5002
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
5003
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
5004
                    WOLFSSL_ERROR(ssl->error);
5005
                    return WOLFSSL_FATAL_ERROR;
5006
                }
5007
#ifdef WOLFSSL_TLS13
5008
            ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
5009
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
5010
            FALL_THROUGH;
5011
5012
        case ACCEPT_CLIENT_HELLO_DONE :
5013
            if (ssl->options.tls1_3) {
5014
                return wolfSSL_accept_TLSv13(ssl);
5015
            }
5016
#endif
5017
5018
            ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
5019
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
5020
            FALL_THROUGH;
5021
5022
        case ACCEPT_FIRST_REPLY_DONE :
5023
            if (ssl->options.returnOnGoodCh) {
5024
                /* Higher level in stack wants us to return. Simulate a
5025
                 * WANT_WRITE to accomplish this. */
5026
                ssl->error = WANT_WRITE;
5027
                return WOLFSSL_FATAL_ERROR;
5028
            }
5029
            if ( (ssl->error = SendServerHello(ssl)) != 0) {
5030
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5031
                WOLFSSL_ERROR(ssl->error);
5032
                return WOLFSSL_FATAL_ERROR;
5033
            }
5034
            ssl->options.acceptState = SERVER_HELLO_SENT;
5035
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
5036
            FALL_THROUGH;
5037
5038
        case SERVER_HELLO_SENT :
5039
        #ifdef WOLFSSL_TLS13
5040
            if (ssl->options.tls1_3) {
5041
                return wolfSSL_accept_TLSv13(ssl);
5042
            }
5043
        #endif
5044
            #ifndef NO_CERTS
5045
                if (!ssl->options.resuming)
5046
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
5047
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5048
                        WOLFSSL_ERROR(ssl->error);
5049
                        return WOLFSSL_FATAL_ERROR;
5050
                    }
5051
            #endif
5052
            ssl->options.acceptState = CERT_SENT;
5053
            WOLFSSL_MSG("accept state CERT_SENT");
5054
            FALL_THROUGH;
5055
5056
        case CERT_SENT :
5057
            #ifndef NO_CERTS
5058
            if (!ssl->options.resuming)
5059
                if ( (ssl->error = SendCertificateStatus(ssl)) != 0) {
5060
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5061
                    WOLFSSL_ERROR(ssl->error);
5062
                    return WOLFSSL_FATAL_ERROR;
5063
                }
5064
            #endif
5065
            ssl->options.acceptState = CERT_STATUS_SENT;
5066
            WOLFSSL_MSG("accept state CERT_STATUS_SENT");
5067
            FALL_THROUGH;
5068
5069
        case CERT_STATUS_SENT :
5070
        #ifdef WOLFSSL_TLS13
5071
            if (ssl->options.tls1_3) {
5072
                return wolfSSL_accept_TLSv13(ssl);
5073
            }
5074
        #endif
5075
            if (!ssl->options.resuming)
5076
                if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
5077
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5078
                    WOLFSSL_ERROR(ssl->error);
5079
                    return WOLFSSL_FATAL_ERROR;
5080
                }
5081
            ssl->options.acceptState = KEY_EXCHANGE_SENT;
5082
            WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
5083
            FALL_THROUGH;
5084
5085
        case KEY_EXCHANGE_SENT :
5086
            #ifndef NO_CERTS
5087
                if (!ssl->options.resuming) {
5088
                    if (ssl->options.verifyPeer) {
5089
                        if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
5090
                            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5091
                            WOLFSSL_ERROR(ssl->error);
5092
                            return WOLFSSL_FATAL_ERROR;
5093
                        }
5094
                    }
5095
                    else {
5096
                        /* SERVER: Peer auth good if not verifying client. */
5097
                        ssl->options.peerAuthGood = 1;
5098
                    }
5099
                }
5100
            #endif
5101
            ssl->options.acceptState = CERT_REQ_SENT;
5102
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
5103
            FALL_THROUGH;
5104
5105
        case CERT_REQ_SENT :
5106
            if (!ssl->options.resuming)
5107
                if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
5108
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5109
                    WOLFSSL_ERROR(ssl->error);
5110
                    return WOLFSSL_FATAL_ERROR;
5111
                }
5112
            ssl->options.acceptState = SERVER_HELLO_DONE;
5113
            WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
5114
            FALL_THROUGH;
5115
5116
        case SERVER_HELLO_DONE :
5117
            if (!ssl->options.resuming) {
5118
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
5119
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
5120
                        WOLFSSL_ERROR(ssl->error);
5121
                        return WOLFSSL_FATAL_ERROR;
5122
                    }
5123
            }
5124
            ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
5125
            WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
5126
            FALL_THROUGH;
5127
5128
        case ACCEPT_SECOND_REPLY_DONE :
5129
        #ifndef NO_CERTS
5130
            /* SERVER: When not resuming and verifying peer but no certificate
5131
             * received and not failing when not received then peer auth good.
5132
             */
5133
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
5134
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
5135
                ssl->options.peerAuthGood = 1;
5136
            }
5137
        #endif /* !NO_CERTS  */
5138
        #ifdef WOLFSSL_NO_CLIENT_AUTH
5139
            if (!ssl->options.resuming) {
5140
                ssl->options.peerAuthGood = 1;
5141
            }
5142
        #endif
5143
5144
#ifdef HAVE_SESSION_TICKET
5145
            if (ssl->options.createTicket && !ssl->options.noTicketTls12) {
5146
                if ( (ssl->error = SendTicket(ssl)) != 0) {
5147
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5148
                    WOLFSSL_MSG("Thought we need ticket but failed");
5149
                    WOLFSSL_ERROR(ssl->error);
5150
                    return WOLFSSL_FATAL_ERROR;
5151
                }
5152
            }
5153
#endif /* HAVE_SESSION_TICKET */
5154
            ssl->options.acceptState = TICKET_SENT;
5155
            WOLFSSL_MSG("accept state  TICKET_SENT");
5156
            FALL_THROUGH;
5157
5158
        case TICKET_SENT:
5159
            /* SERVER: Fail-safe for CLient Authentication. */
5160
            if (!ssl->options.peerAuthGood) {
5161
                WOLFSSL_MSG("Client authentication did not happen");
5162
                return WOLFSSL_FATAL_ERROR;
5163
            }
5164
5165
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
5166
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5167
                WOLFSSL_ERROR(ssl->error);
5168
                return WOLFSSL_FATAL_ERROR;
5169
            }
5170
            ssl->options.acceptState = CHANGE_CIPHER_SENT;
5171
            WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
5172
            FALL_THROUGH;
5173
5174
        case CHANGE_CIPHER_SENT :
5175
            if ( (ssl->error = SendFinished(ssl)) != 0) {
5176
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
5177
                WOLFSSL_ERROR(ssl->error);
5178
                return WOLFSSL_FATAL_ERROR;
5179
            }
5180
5181
            ssl->options.acceptState = ACCEPT_FINISHED_DONE;
5182
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
5183
            FALL_THROUGH;
5184
5185
        case ACCEPT_FINISHED_DONE :
5186
            if (ssl->options.resuming) {
5187
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
5188
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
5189
                        WOLFSSL_ERROR(ssl->error);
5190
                        return WOLFSSL_FATAL_ERROR;
5191
                    }
5192
                }
5193
            }
5194
            ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
5195
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
5196
            FALL_THROUGH;
5197
5198
        case ACCEPT_THIRD_REPLY_DONE :
5199
#ifndef NO_HANDSHAKE_DONE_CB
5200
            if (ssl->hsDoneCb) {
5201
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
5202
                if (cbret < 0) {
5203
                    ssl->error = cbret;
5204
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
5205
                    return WOLFSSL_FATAL_ERROR;
5206
                }
5207
            }
5208
#endif /* NO_HANDSHAKE_DONE_CB */
5209
5210
            if (!ssl->options.dtls) {
5211
                if (!ssl->options.keepResources) {
5212
                    FreeHandshakeResources(ssl);
5213
                }
5214
            }
5215
#ifdef WOLFSSL_DTLS
5216
            else {
5217
                ssl->options.dtlsHsRetain = 1;
5218
            }
5219
#endif /* WOLFSSL_DTLS */
5220
5221
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
5222
            /* This may be necessary in async so that we don't try to
5223
             * renegotiate again */
5224
            if (ssl->secure_renegotiation &&
5225
                    ssl->secure_renegotiation->startScr) {
5226
                ssl->secure_renegotiation->startScr = 0;
5227
            }
5228
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
5229
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
5230
            /* Free the remaining async context if not using it for crypto */
5231
            FreeAsyncCtx(ssl, 1);
5232
#endif
5233
5234
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
5235
            if (ssl->dtls_export) {
5236
                if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
5237
                    WOLFSSL_MSG("Export DTLS session error");
5238
                    WOLFSSL_ERROR(ssl->error);
5239
                    return WOLFSSL_FATAL_ERROR;
5240
                }
5241
            }
5242
#endif
5243
            ssl->error = 0; /* clear the error */
5244
5245
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
5246
            return WOLFSSL_SUCCESS;
5247
5248
        default:
5249
            WOLFSSL_MSG("Unknown accept state ERROR");
5250
            return WOLFSSL_FATAL_ERROR;
5251
        }
5252
#endif /* !WOLFSSL_NO_TLS12 */
5253
    }
5254
5255
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
5256
/* end server only parts */
5257
5258
5259
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
5260
struct chGoodDisableReadCbCtx {
5261
    ClientHelloGoodCb userCb;
5262
    void*             userCtx;
5263
};
5264
5265
static int chGoodDisableReadCB(WOLFSSL* ssl, void* ctx)
5266
{
5267
    struct chGoodDisableReadCbCtx* cb = (struct chGoodDisableReadCbCtx*)ctx;
5268
    int ret = 0;
5269
    if (cb->userCb != NULL)
5270
        ret = cb->userCb(ssl, cb->userCtx);
5271
    if (ret >= 0)
5272
        wolfSSL_SSLDisableRead(ssl);
5273
    return ret;
5274
}
5275
5276
/**
5277
 * Statelessly listen for a connection
5278
 * @param ssl The ssl object to use for listening to connections
5279
 * @return WOLFSSL_SUCCESS - ClientHello containing a valid cookie was received
5280
 *                           The connection can be continued with wolfSSL_accept
5281
 *         WOLFSSL_FAILURE - The I/O layer returned WANT_READ. This is either
5282
 *                           because there is no data to read and we are using
5283
 *                           non-blocking sockets or we sent a cookie request
5284
 *                           and we are waiting for a reply. The user should
5285
 *                           call wolfDTLS_accept_stateless again after data
5286
 *                           becomes available in the I/O layer.
5287
 *         WOLFSSL_FATAL_ERROR - A fatal error occurred. The ssl object should
5288
 *                           be free'd and allocated again to continue.
5289
 */
5290
int wolfDTLS_accept_stateless(WOLFSSL* ssl)
5291
{
5292
    byte disableRead;
5293
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
5294
    struct chGoodDisableReadCbCtx cb;
5295
5296
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
5297
5298
    if (ssl == NULL)
5299
        return WOLFSSL_FATAL_ERROR;
5300
5301
    /* Save this to restore it later */
5302
    disableRead = (byte)ssl->options.disableRead;
5303
    cb.userCb = ssl->chGoodCb;
5304
    cb.userCtx = ssl->chGoodCtx;
5305
5306
    /* Register our own callback so that we can disable reading */
5307
    if (wolfDTLS_SetChGoodCb(ssl, chGoodDisableReadCB, &cb) != WOLFSSL_SUCCESS)
5308
        return WOLFSSL_FATAL_ERROR;
5309
5310
    ssl->options.returnOnGoodCh = 1;
5311
    ret = wolfSSL_accept(ssl);
5312
    ssl->options.returnOnGoodCh = 0;
5313
    /* restore user options */
5314
    ssl->options.disableRead = disableRead;
5315
    (void)wolfDTLS_SetChGoodCb(ssl, cb.userCb, cb.userCtx);
5316
    if (ret == WOLFSSL_SUCCESS) {
5317
        WOLFSSL_MSG("should not happen. maybe the user called "
5318
                    "wolfDTLS_accept_stateless instead of wolfSSL_accept");
5319
    }
5320
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_READ) ||
5321
             ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
5322
        ssl->error = 0;
5323
        if (ssl->options.dtlsStateful)
5324
            ret = WOLFSSL_SUCCESS;
5325
        else
5326
            ret = WOLFSSL_FAILURE;
5327
    }
5328
    else {
5329
        ret = WOLFSSL_FATAL_ERROR;
5330
    }
5331
    return ret;
5332
}
5333
5334
/* WC_NO_INLINE: wolfDTLS_accept_stateless passes the address of a stack-local
5335
 * context here; the restore call before return clears it again. Preventing
5336
 * inlining hides that cross-frame assignment from GCC's -Wdangling-pointer
5337
 * analysis, which otherwise flags a false positive on GCC 14+. */
5338
WC_NO_INLINE
5339
int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx)
5340
{
5341
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
5342
5343
    if (ssl == NULL)
5344
        return BAD_FUNC_ARG;
5345
5346
    ssl->chGoodCb  = cb;
5347
    ssl->chGoodCtx = user_ctx;
5348
5349
    return WOLFSSL_SUCCESS;
5350
}
5351
#endif
5352
5353
#ifndef NO_HANDSHAKE_DONE_CB
5354
5355
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
5356
0
{
5357
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
5358
5359
0
    if (ssl == NULL)
5360
0
        return BAD_FUNC_ARG;
5361
5362
0
    ssl->hsDoneCb  = cb;
5363
0
    ssl->hsDoneCtx = user_ctx;
5364
5365
0
    return WOLFSSL_SUCCESS;
5366
0
}
5367
5368
#endif /* NO_HANDSHAKE_DONE_CB */
5369
5370
WOLFSSL_ABI
5371
int wolfSSL_Cleanup(void)
5372
24.2k
{
5373
24.2k
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
5374
24.2k
    int release = 0;
5375
24.2k
#if !defined(NO_SESSION_CACHE)
5376
24.2k
    int i;
5377
24.2k
    int j;
5378
24.2k
#endif
5379
5380
24.2k
    WOLFSSL_ENTER("wolfSSL_Cleanup");
5381
5382
#ifndef WOLFSSL_MUTEX_INITIALIZER
5383
    if (inits_count_mutex_valid == 1) {
5384
#endif
5385
24.2k
        if (wc_LockMutex(&inits_count_mutex) != 0) {
5386
0
            WOLFSSL_MSG("Bad Lock Mutex count");
5387
0
            return BAD_MUTEX_E;
5388
0
        }
5389
#ifndef WOLFSSL_MUTEX_INITIALIZER
5390
    }
5391
#endif
5392
5393
24.2k
    if (initRefCount > 0) {
5394
5.48k
        initRefCount = initRefCount - 1;
5395
5.48k
        if (initRefCount == 0)
5396
5.48k
            release = 1;
5397
5.48k
    }
5398
5399
#ifndef WOLFSSL_MUTEX_INITIALIZER
5400
    if (inits_count_mutex_valid == 1) {
5401
#endif
5402
24.2k
        wc_UnLockMutex(&inits_count_mutex);
5403
#ifndef WOLFSSL_MUTEX_INITIALIZER
5404
    }
5405
#endif
5406
5407
24.2k
    if (!release)
5408
18.7k
        return ret;
5409
5410
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5411
    wolfSSL_crypto_policy_disable();
5412
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5413
5414
#ifdef OPENSSL_EXTRA
5415
    wolfSSL_BN_free_one();
5416
#endif
5417
5418
5.48k
#ifndef NO_SESSION_CACHE
5419
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
5420
    for (i = 0; i < SESSION_ROWS; ++i) {
5421
        if ((SessionCache[i].lock_valid == 1) &&
5422
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
5423
            if (ret == WOLFSSL_SUCCESS)
5424
                ret = BAD_MUTEX_E;
5425
        }
5426
        SessionCache[i].lock_valid = 0;
5427
    }
5428
    #else
5429
5.48k
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
5430
0
        if (ret == WOLFSSL_SUCCESS)
5431
0
            ret = BAD_MUTEX_E;
5432
0
    }
5433
5.48k
    session_lock_valid = 0;
5434
5.48k
    #endif
5435
65.7k
    for (i = 0; i < SESSION_ROWS; i++) {
5436
241k
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
5437
    #ifdef SESSION_CACHE_DYNAMIC_MEM
5438
            if (SessionCache[i].Sessions[j]) {
5439
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
5440
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
5441
                      DYNAMIC_TYPE_SESSION);
5442
                SessionCache[i].Sessions[j] = NULL;
5443
            }
5444
    #else
5445
180k
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
5446
180k
    #endif
5447
180k
        }
5448
60.2k
    }
5449
5.48k
    #ifndef NO_CLIENT_CACHE
5450
    #ifndef WOLFSSL_MUTEX_INITIALIZER
5451
    if ((clisession_mutex_valid == 1) &&
5452
        (wc_FreeMutex(&clisession_mutex) != 0)) {
5453
        if (ret == WOLFSSL_SUCCESS)
5454
            ret = BAD_MUTEX_E;
5455
    }
5456
    clisession_mutex_valid = 0;
5457
    #endif
5458
5.48k
    #endif
5459
5.48k
#endif /* !NO_SESSION_CACHE */
5460
5461
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
5462
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5463
    if ((inits_count_mutex_valid == 1) &&
5464
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
5465
        if (ret == WOLFSSL_SUCCESS)
5466
            ret = BAD_MUTEX_E;
5467
    }
5468
    inits_count_mutex_valid = 0;
5469
#endif
5470
5471
#ifdef OPENSSL_EXTRA
5472
    wolfSSL_RAND_Cleanup();
5473
#endif
5474
5475
5.48k
    if (wolfCrypt_Cleanup() != 0) {
5476
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
5477
0
        if (ret == WOLFSSL_SUCCESS)
5478
0
            ret = WC_CLEANUP_E;
5479
0
    }
5480
5481
#if FIPS_VERSION_GE(5,1)
5482
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
5483
        if (ret == WOLFSSL_SUCCESS)
5484
            ret = WC_CLEANUP_E;
5485
    }
5486
#endif
5487
5488
5.48k
#ifdef HAVE_GLOBAL_RNG
5489
#ifndef WOLFSSL_MUTEX_INITIALIZER
5490
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
5491
        if (ret == WOLFSSL_SUCCESS)
5492
            ret = BAD_MUTEX_E;
5493
    }
5494
    globalRNGMutex_valid = 0;
5495
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
5496
5497
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
5498
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
5499
    gDrbgDefCtx = NULL;
5500
    #endif
5501
5.48k
#endif
5502
5503
#ifdef HAVE_EX_DATA_CRYPTO
5504
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
5505
    crypto_ex_cb_ctx_session = NULL;
5506
#endif
5507
5508
#ifdef WOLFSSL_MEM_FAIL_COUNT
5509
    wc_MemFailCount_Free();
5510
#endif
5511
5512
5.48k
    return ret;
5513
24.2k
}
5514
5515
/* Returns 1 if name is a syntactically valid DNS FQDN per RFC 952/1123.
5516
 *
5517
 * Rules enforced:
5518
 *   - Total effective length (excluding optional trailing dot) in [1, 253]
5519
 *   - Each label is 1-63 octets of [a-zA-Z0-9-], with _ allowed in all but
5520
 *     the last label.
5521
 *   - No label starts or ends with '-'
5522
 *   - At least two labels (single-label names are not "fully qualified")
5523
 *   - Final label (TLD) contains at least one letter (rejects all-numeric
5524
 *     strings that could be confused with IPv4 literals, and matches the
5525
 *     ICANN constraint that TLDs are alphabetic)
5526
 *   - Optional trailing dot is accepted (absolute FQDN form)
5527
 *   - Internationalized names are valid in their ACE/punycode (xn--) form
5528
 */
5529
int wolfssl_local_IsValidFQDN(const char* name, word32 nameSz)
5530
0
{
5531
0
    word32 i;
5532
0
    int labelLen = 0;
5533
0
    int labelCount = 0;
5534
0
    int curLabelHasAlpha = 0;
5535
0
    int curLabelHasUnderscore = 0;
5536
5537
0
    if (name == NULL || nameSz == 0)
5538
0
        return 0;
5539
5540
    /* Strip a single optional trailing dot before measuring.  "example.com."
5541
     * is the absolute form of the same FQDN.
5542
     */
5543
0
    if (name[nameSz - 1] == '.')
5544
0
        --nameSz;
5545
5546
0
    if (nameSz < 1 || nameSz > 253)
5547
0
        return 0;
5548
5549
0
    for (i = 0; i < nameSz; i++) {
5550
0
        byte c = (byte)name[i];
5551
5552
0
        if (c == '.') {
5553
0
            if (labelLen == 0 || name[i - 1] == '-')
5554
0
                return 0;
5555
0
            ++labelCount;
5556
0
            labelLen = 0;
5557
0
            curLabelHasAlpha = 0;
5558
0
            curLabelHasUnderscore = 0;
5559
0
            continue;
5560
0
        }
5561
5562
0
        if (++labelLen > 63)
5563
0
            return 0;
5564
5565
0
        if (c == '-') {
5566
0
            if (labelLen == 1)
5567
0
                return 0;
5568
0
        }
5569
0
        else if (((c | 0x20) >= 'a') && ((c | 0x20) <= 'z')) {
5570
0
            curLabelHasAlpha = 1;
5571
0
        }
5572
0
        else if (c == '_') {
5573
0
            curLabelHasUnderscore = 1;
5574
0
        }
5575
0
        else if ((c < '0') || (c > '9')) {
5576
0
            return 0;
5577
0
        }
5578
0
    }
5579
5580
    /* Final label (no trailing dot in the effective range to close it) */
5581
0
    if ((labelLen == 0) || (name[nameSz - 1] == '-') || curLabelHasUnderscore)
5582
0
        return 0;
5583
0
    ++labelCount;
5584
5585
0
    return ((labelCount > 1) && curLabelHasAlpha);
5586
0
}
5587
5588
/* call before SSL_connect, if verifying will add name check to
5589
   date check and signature check */
5590
WOLFSSL_ABI
5591
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
5592
0
{
5593
0
    size_t dn_len;
5594
5595
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
5596
5597
0
    if (ssl == NULL || dn == NULL) {
5598
0
        WOLFSSL_MSG("Bad function argument: NULL");
5599
0
        return WOLFSSL_FAILURE;
5600
0
    }
5601
5602
0
    dn_len = XSTRLEN(dn);
5603
5604
0
    if ((! wolfssl_local_IsValidFQDN(dn, (word32)dn_len)) &&
5605
0
        (XSTRCMP(dn, "localhost") != 0))
5606
0
    {
5607
0
        WOLFSSL_MSG("Bad function argument: fails wolfssl_local_IsValidFQDN");
5608
0
        return WOLFSSL_FAILURE;
5609
0
    }
5610
5611
0
    if (ssl->buffers.domainName.buffer)
5612
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5613
5614
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
5615
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
5616
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5617
5618
0
    if (ssl->buffers.domainName.buffer) {
5619
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
5620
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
5621
0
        domainName[ssl->buffers.domainName.length] = '\0';
5622
0
        return WOLFSSL_SUCCESS;
5623
0
    }
5624
0
    else {
5625
0
        ssl->error = MEMORY_ERROR;
5626
0
        return WOLFSSL_FAILURE;
5627
0
    }
5628
0
}
5629
5630
/* call before SSL_connect, if verifying will add IP SAN check to
5631
   date check and signature check */
5632
WOLFSSL_ABI
5633
int wolfSSL_check_ip_address(WOLFSSL* ssl, const char* ipaddr)
5634
0
{
5635
0
    WOLFSSL_ENTER("wolfSSL_check_ip_address");
5636
5637
0
    if (ssl == NULL || ipaddr == NULL) {
5638
0
        WOLFSSL_MSG("Bad function argument: NULL");
5639
0
        return WOLFSSL_FAILURE;
5640
0
    }
5641
5642
0
    if (ssl->buffers.ipasc.buffer != NULL) {
5643
0
        XFREE(ssl->buffers.ipasc.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
5644
0
        ssl->buffers.ipasc.buffer = NULL;
5645
0
        ssl->buffers.ipasc.length = 0;
5646
0
    }
5647
5648
0
    ssl->buffers.ipasc.length = (word32)XSTRLEN(ipaddr);
5649
0
    ssl->buffers.ipasc.buffer = (byte*)XMALLOC(ssl->buffers.ipasc.length + 1,
5650
0
                                               ssl->heap, DYNAMIC_TYPE_DOMAIN);
5651
0
    if (ssl->buffers.ipasc.buffer == NULL) {
5652
0
        ssl->error = MEMORY_ERROR;
5653
0
        return WOLFSSL_FAILURE;
5654
0
    }
5655
5656
0
    XMEMCPY(ssl->buffers.ipasc.buffer, ipaddr, ssl->buffers.ipasc.length);
5657
0
    ssl->buffers.ipasc.buffer[ssl->buffers.ipasc.length] = '\0';
5658
5659
#ifdef OPENSSL_EXTRA
5660
    if (ssl->param == NULL) {
5661
        return WOLFSSL_FAILURE;
5662
    }
5663
    if (wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(ssl->param, ipaddr) !=
5664
            WOLFSSL_SUCCESS) {
5665
        return WOLFSSL_FAILURE;
5666
    }
5667
#endif
5668
5669
0
    return WOLFSSL_SUCCESS;
5670
0
}
5671
5672
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
5673
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
5674
    if (ssl == NULL) {
5675
        return NULL;
5676
    }
5677
5678
    if (ssl->buffers.domainName.buffer)
5679
        return (const char *)ssl->buffers.domainName.buffer;
5680
    else if (ssl->session && ssl->session->peer)
5681
        return ssl->session->peer->subjectCN;
5682
#ifdef KEEP_PEER_CERT
5683
    else if (ssl->peerCert.subjectCN[0])
5684
        return ssl->peerCert.subjectCN;
5685
#endif
5686
    else {
5687
        ssl->error = NO_PEER_CERT;
5688
        return NULL;
5689
    }
5690
}
5691
5692
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
5693
5694
/* turn on wolfSSL zlib compression
5695
   returns WOLFSSL_SUCCESS for success, else error (not built in)
5696
*/
5697
int wolfSSL_set_compression(WOLFSSL* ssl)
5698
0
{
5699
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
5700
0
    (void)ssl;
5701
#ifdef HAVE_LIBZ
5702
    ssl->options.usingCompression = 1;
5703
    return WOLFSSL_SUCCESS;
5704
#else
5705
0
    return NOT_COMPILED_IN;
5706
0
#endif
5707
0
}
5708
5709
5710
#ifndef USE_WINDOWS_API
5711
    #if !defined(NO_WRITEV) && !defined(NO_TLS)
5712
5713
        /* simulate writev semantics, doesn't actually do block at a time though
5714
           because of SSL_write behavior and because front adds may be small */
5715
        int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt)
5716
0
        {
5717
0
        #ifdef WOLFSSL_SMALL_STACK
5718
0
            byte   staticBuffer[1]; /* force heap usage */
5719
        #else
5720
            byte   staticBuffer[FILE_BUFFER_SIZE];
5721
        #endif
5722
0
            byte* myBuffer  = staticBuffer;
5723
0
            int   dynamic   = 0;
5724
0
            size_t sending   = 0;
5725
0
            size_t idx       = 0;
5726
0
            int   i;
5727
0
            int   ret;
5728
5729
0
            WOLFSSL_ENTER("wolfSSL_writev");
5730
5731
0
            for (i = 0; i < iovcnt; i++)
5732
0
                if (! WC_SAFE_SUM_UNSIGNED(size_t, sending, iov[i].iov_len,
5733
0
                                           sending))
5734
0
                    return BUFFER_E;
5735
5736
0
            if (sending > sizeof(staticBuffer)) {
5737
0
                myBuffer = (byte*)XMALLOC(sending, ssl->heap,
5738
0
                                          DYNAMIC_TYPE_WRITEV);
5739
0
                if (!myBuffer)
5740
0
                    return MEMORY_ERROR;
5741
5742
0
                dynamic = 1;
5743
0
            }
5744
5745
0
            for (i = 0; i < iovcnt; i++) {
5746
0
                XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
5747
0
                idx += (int)iov[i].iov_len;
5748
0
            }
5749
5750
           /* myBuffer may not be initialized fully, but the span up to the
5751
            * sending length will be.
5752
            */
5753
0
            PRAGMA_GCC_DIAG_PUSH
5754
0
            PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
5755
0
            ret = wolfSSL_write_internal(ssl, myBuffer, sending);
5756
0
            PRAGMA_GCC_DIAG_POP
5757
5758
0
            if (dynamic)
5759
0
                XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
5760
5761
0
            return ret;
5762
0
        }
5763
    #endif
5764
#endif
5765
5766
5767
#ifdef WOLFSSL_CALLBACKS
5768
5769
    typedef struct itimerval Itimerval;
5770
5771
    /* don't keep calling simple functions while setting up timer and signals
5772
       if no inlining these are the next best */
5773
5774
    #define AddTimes(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 >=  1000000) {          \
5779
                (c).tv_sec++;                       \
5780
                (c).tv_usec -= 1000000;             \
5781
            }                                       \
5782
        } while (0)
5783
5784
5785
    #define SubtractTimes(a, b, c)                  \
5786
        do {                                        \
5787
            (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
5788
            (c).tv_usec = (a).tv_usec - (b).tv_usec;\
5789
            if ((c).tv_usec < 0) {                  \
5790
                (c).tv_sec--;                       \
5791
                (c).tv_usec += 1000000;             \
5792
            }                                       \
5793
        } while (0)
5794
5795
    #define CmpTimes(a, b, cmp)                     \
5796
        (((a).tv_sec  ==  (b).tv_sec) ?             \
5797
            ((a).tv_usec cmp (b).tv_usec) :         \
5798
            ((a).tv_sec  cmp (b).tv_sec))           \
5799
5800
5801
    /* do nothing handler */
5802
    static void myHandler(int signo)
5803
    {
5804
        (void)signo;
5805
        return;
5806
    }
5807
5808
5809
    static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
5810
                                 TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5811
    {
5812
        int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
5813
        int       oldTimerOn = 0;   /* was timer already on */
5814
        WOLFSSL_TIMEVAL startTime;
5815
        WOLFSSL_TIMEVAL endTime;
5816
        WOLFSSL_TIMEVAL totalTime;
5817
        Itimerval myTimeout;
5818
        Itimerval oldTimeout; /* if old timer adjust from total time to reset */
5819
        struct sigaction act, oact;
5820
5821
        #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; }
5822
5823
        if (hsCb) {
5824
            ssl->hsInfoOn = 1;
5825
            InitHandShakeInfo(&ssl->handShakeInfo, ssl);
5826
        }
5827
        if (toCb) {
5828
            ssl->toInfoOn = 1;
5829
            InitTimeoutInfo(&ssl->timeoutInfo);
5830
5831
            if (gettimeofday(&startTime, 0) < 0)
5832
                ERR_OUT(GETTIME_ERROR);
5833
5834
            /* use setitimer to simulate getitimer, init 0 myTimeout */
5835
            myTimeout.it_interval.tv_sec  = 0;
5836
            myTimeout.it_interval.tv_usec = 0;
5837
            myTimeout.it_value.tv_sec     = 0;
5838
            myTimeout.it_value.tv_usec    = 0;
5839
            if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0)
5840
                ERR_OUT(SETITIMER_ERROR);
5841
5842
            if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) {
5843
                oldTimerOn = 1;
5844
5845
                /* is old timer going to expire before ours */
5846
                if (CmpTimes(oldTimeout.it_value, timeout, <)) {
5847
                    timeout.tv_sec  = oldTimeout.it_value.tv_sec;
5848
                    timeout.tv_usec = oldTimeout.it_value.tv_usec;
5849
                }
5850
            }
5851
            myTimeout.it_value.tv_sec  = timeout.tv_sec;
5852
            myTimeout.it_value.tv_usec = timeout.tv_usec;
5853
5854
            /* set up signal handler, don't restart socket send/recv */
5855
            act.sa_handler = myHandler;
5856
            sigemptyset(&act.sa_mask);
5857
            act.sa_flags = 0;
5858
#ifdef SA_INTERRUPT
5859
            act.sa_flags |= SA_INTERRUPT;
5860
#endif
5861
            if (sigaction(SIGALRM, &act, &oact) < 0)
5862
                ERR_OUT(SIGACT_ERROR);
5863
5864
            if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0)
5865
                ERR_OUT(SETITIMER_ERROR);
5866
        }
5867
5868
        /* do main work */
5869
#ifndef NO_WOLFSSL_CLIENT
5870
        if (ssl->options.side == WOLFSSL_CLIENT_END)
5871
            ret = wolfSSL_connect(ssl);
5872
#endif
5873
#ifndef NO_WOLFSSL_SERVER
5874
        if (ssl->options.side == WOLFSSL_SERVER_END)
5875
            ret = wolfSSL_accept(ssl);
5876
#endif
5877
5878
        /* do callbacks */
5879
        if (toCb) {
5880
            if (oldTimerOn) {
5881
                if (gettimeofday(&endTime, 0) < 0)
5882
                    ERR_OUT(SYSLIB_FAILED_E);
5883
                SubtractTimes(endTime, startTime, totalTime);
5884
                /* adjust old timer for elapsed time */
5885
                if (CmpTimes(totalTime, oldTimeout.it_value, <))
5886
                    SubtractTimes(oldTimeout.it_value, totalTime,
5887
                                  oldTimeout.it_value);
5888
                else {
5889
                    /* reset value to interval, may be off */
5890
                    oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec;
5891
                    oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec;
5892
                }
5893
                /* keep iter the same whether there or not */
5894
            }
5895
            /* restore old handler */
5896
            if (sigaction(SIGALRM, &oact, 0) < 0)
5897
                ret = SIGACT_ERROR;    /* more pressing error, stomp */
5898
            else
5899
                /* use old settings which may turn off (expired or not there) */
5900
                if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0)
5901
                    ret = SETITIMER_ERROR;
5902
5903
            /* if we had a timeout call callback */
5904
            if (ssl->timeoutInfo.timeoutName[0]) {
5905
                ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
5906
                ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
5907
                (toCb)(&ssl->timeoutInfo);
5908
            }
5909
            ssl->toInfoOn = 0;
5910
        }
5911
5912
        /* clean up buffers allocated by AddPacketInfo */
5913
        FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
5914
5915
        if (hsCb) {
5916
            FinishHandShakeInfo(&ssl->handShakeInfo);
5917
            (hsCb)(&ssl->handShakeInfo);
5918
            ssl->hsInfoOn = 0;
5919
        }
5920
        return ret;
5921
    }
5922
5923
5924
#ifndef NO_WOLFSSL_CLIENT
5925
5926
    int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
5927
                          TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5928
    {
5929
        WOLFSSL_ENTER("wolfSSL_connect_ex");
5930
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
5931
    }
5932
5933
#endif
5934
5935
5936
#ifndef NO_WOLFSSL_SERVER
5937
5938
    int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
5939
                         TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
5940
    {
5941
        WOLFSSL_ENTER("wolfSSL_accept_ex");
5942
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
5943
    }
5944
5945
#endif
5946
5947
#endif /* WOLFSSL_CALLBACKS */
5948
5949
5950
#ifndef NO_PSK
5951
5952
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
5953
                                         wc_psk_client_callback cb)
5954
    {
5955
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
5956
5957
        if (ctx == NULL)
5958
            return;
5959
5960
        ctx->havePSK = 1;
5961
        ctx->client_psk_cb = cb;
5962
    }
5963
5964
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
5965
    {
5966
        byte haveRSA = 1;
5967
        int  keySz   = 0;
5968
5969
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
5970
5971
        if (ssl == NULL)
5972
            return;
5973
5974
        ssl->options.havePSK = 1;
5975
        ssl->options.client_psk_cb = cb;
5976
5977
        #ifdef NO_RSA
5978
            haveRSA = 0;
5979
        #endif
5980
        #ifndef NO_CERTS
5981
            keySz = ssl->buffers.keySz;
5982
        #endif
5983
        if (AllocateSuites(ssl) != 0)
5984
            return;
5985
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
5986
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
5987
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
5988
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
5989
    }
5990
5991
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
5992
    int wolfSSL_CTX_set_cert_with_extern_psk(WOLFSSL_CTX* ctx, int state)
5993
    {
5994
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_with_extern_psk");
5995
        if (ctx == NULL)
5996
            return WOLFSSL_FAILURE;
5997
        ctx->certWithExternPsk = (byte)(state != 0);
5998
        return WOLFSSL_SUCCESS;
5999
    }
6000
6001
    int wolfSSL_set_cert_with_extern_psk(WOLFSSL* ssl, int state)
6002
    {
6003
        WOLFSSL_ENTER("wolfSSL_set_cert_with_extern_psk");
6004
        if (ssl == NULL)
6005
            return WOLFSSL_FAILURE;
6006
        ssl->options.certWithExternPsk = (word16)(state != 0);
6007
        return WOLFSSL_SUCCESS;
6008
    }
6009
#endif
6010
6011
    #ifdef OPENSSL_EXTRA
6012
    /**
6013
     * set call back function for psk session use
6014
     * @param ssl  a pointer to WOLFSSL structure
6015
     * @param cb   a function pointer to wc_psk_use_session_cb
6016
     * @return none
6017
     */
6018
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
6019
                                                wc_psk_use_session_cb_func cb)
6020
    {
6021
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
6022
6023
        if (ssl != NULL) {
6024
            ssl->options.havePSK = 1;
6025
            ssl->options.session_psk_cb = cb;
6026
        }
6027
6028
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
6029
    }
6030
    #endif
6031
6032
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
6033
                                         wc_psk_server_callback cb)
6034
    {
6035
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
6036
        if (ctx == NULL)
6037
            return;
6038
        ctx->havePSK = 1;
6039
        ctx->server_psk_cb = cb;
6040
    }
6041
6042
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
6043
    {
6044
        byte haveRSA = 1;
6045
        int  keySz   = 0;
6046
6047
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
6048
        if (ssl == NULL)
6049
            return;
6050
6051
        ssl->options.havePSK = 1;
6052
        ssl->options.server_psk_cb = cb;
6053
6054
        #ifdef NO_RSA
6055
            haveRSA = 0;
6056
        #endif
6057
        #ifndef NO_CERTS
6058
            keySz = ssl->buffers.keySz;
6059
        #endif
6060
        if (AllocateSuites(ssl) != 0)
6061
            return;
6062
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
6063
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
6064
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
6065
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
6066
    }
6067
6068
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
6069
    {
6070
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
6071
6072
        if (ssl == NULL || ssl->arrays == NULL)
6073
            return NULL;
6074
6075
        return ssl->arrays->server_hint;
6076
    }
6077
6078
6079
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
6080
    {
6081
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
6082
6083
        if (ssl == NULL || ssl->arrays == NULL)
6084
            return NULL;
6085
6086
        return ssl->arrays->client_identity;
6087
    }
6088
6089
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
6090
    {
6091
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
6092
        if (hint == 0)
6093
            ctx->server_hint[0] = '\0';
6094
        else {
6095
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
6096
            #ifdef WOLFSSL_QT
6097
            ctx->havePSK=1;
6098
            #endif
6099
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
6100
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
6101
        }
6102
        return WOLFSSL_SUCCESS;
6103
    }
6104
6105
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
6106
    {
6107
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
6108
6109
        if (ssl == NULL || ssl->arrays == NULL)
6110
            return WOLFSSL_FAILURE;
6111
6112
        if (hint == 0)
6113
            ssl->arrays->server_hint[0] = 0;
6114
        else {
6115
            XSTRNCPY(ssl->arrays->server_hint, hint,
6116
                                            sizeof(ssl->arrays->server_hint)-1);
6117
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
6118
        }
6119
        return WOLFSSL_SUCCESS;
6120
    }
6121
6122
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
6123
    {
6124
        return ssl ? ssl->options.psk_ctx : NULL;
6125
    }
6126
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
6127
    {
6128
        return ctx ? ctx->psk_ctx : NULL;
6129
    }
6130
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
6131
    {
6132
        if (ssl == NULL)
6133
            return WOLFSSL_FAILURE;
6134
        ssl->options.psk_ctx = psk_ctx;
6135
        return WOLFSSL_SUCCESS;
6136
    }
6137
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
6138
    {
6139
        if (ctx == NULL)
6140
            return WOLFSSL_FAILURE;
6141
        ctx->psk_ctx = psk_ctx;
6142
        return WOLFSSL_SUCCESS;
6143
    }
6144
#endif /* NO_PSK */
6145
6146
6147
#ifdef HAVE_ANON
6148
6149
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
6150
    {
6151
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
6152
6153
        if (ctx == NULL)
6154
            return WOLFSSL_FAILURE;
6155
6156
        ctx->useAnon = 1;
6157
6158
        return WOLFSSL_SUCCESS;
6159
    }
6160
6161
#endif /* HAVE_ANON */
6162
6163
#ifdef OPENSSL_EXTRA
6164
6165
    int wolfSSL_add_all_algorithms(void)
6166
    {
6167
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
6168
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
6169
            return WOLFSSL_SUCCESS;
6170
        else
6171
            return WOLFSSL_FATAL_ERROR;
6172
    }
6173
6174
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
6175
    {
6176
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
6177
6178
        if  (wolfSSL_add_all_algorithms() ==
6179
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
6180
        {
6181
            return WOLFSSL_FATAL_ERROR;
6182
        }
6183
6184
        return  WOLFSSL_SUCCESS;
6185
    }
6186
6187
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
6188
    {
6189
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
6190
        /* This function is currently the same as
6191
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
6192
        the use of a wolfssl.cnf type configuration file and is only used for
6193
        OpenSSL compatibility. */
6194
6195
        if (wolfSSL_add_all_algorithms() ==
6196
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
6197
        {
6198
            return WOLFSSL_FATAL_ERROR;
6199
        }
6200
        return WOLFSSL_SUCCESS;
6201
    }
6202
6203
#endif
6204
6205
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
6206
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
6207
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
6208
    {
6209
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
6210
        if (mode)
6211
            ctx->quietShutdown = 1;
6212
    }
6213
6214
6215
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
6216
    {
6217
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
6218
        if (mode)
6219
            ssl->options.quietShutdown = 1;
6220
    }
6221
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
6222
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
6223
6224
#ifdef OPENSSL_EXTRA
6225
#ifndef NO_BIO
6226
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
6227
    {
6228
        WOLFSSL_ENTER("wolfSSL_set_bio");
6229
6230
        if (ssl == NULL) {
6231
            WOLFSSL_MSG("Bad argument, ssl was NULL");
6232
            return;
6233
        }
6234
6235
        /* free any existing WOLFSSL_BIOs in use but don't free those in
6236
         * a chain */
6237
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
6238
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
6239
                if (ssl->biowr != NULL && ssl->biowr->prev == NULL)
6240
                    wolfSSL_BIO_free(ssl->biowr);
6241
                ssl->biowr = NULL;
6242
            }
6243
            if (ssl->biord->prev == NULL)
6244
                wolfSSL_BIO_free(ssl->biord);
6245
            ssl->biord = NULL;
6246
        }
6247
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
6248
            if (ssl->biowr->prev == NULL)
6249
                wolfSSL_BIO_free(ssl->biowr);
6250
            ssl->biowr = NULL;
6251
        }
6252
6253
        /* set flag obviously */
6254
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
6255
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
6256
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
6257
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
6258
6259
        if (flags & WOLFSSL_BIO_FLAG_READ)
6260
            ssl->biord = rd;
6261
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
6262
            ssl->biowr = wr;
6263
6264
        /* set SSL to use BIO callbacks instead */
6265
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
6266
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
6267
        {
6268
            ssl->CBIORecv = SslBioReceive;
6269
        }
6270
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
6271
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
6272
        {
6273
            ssl->CBIOSend = SslBioSend;
6274
        }
6275
6276
        /* User programs should always retry reading from these BIOs */
6277
        if (rd) {
6278
            /* User writes to rd */
6279
            wolfSSL_BIO_set_retry_write(rd);
6280
        }
6281
        if (wr) {
6282
            /* User reads from wr */
6283
            wolfSSL_BIO_set_retry_read(wr);
6284
        }
6285
    }
6286
6287
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
6288
    {
6289
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
6290
    }
6291
6292
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
6293
    {
6294
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
6295
    }
6296
6297
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
6298
    {
6299
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
6300
    }
6301
6302
#endif /* !NO_BIO */
6303
#endif /* OPENSSL_EXTRA */
6304
6305
#ifdef WOLFSSL_CERT_SETUP_CB
6306
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
6307
    /* registers client cert callback, called during handshake if server
6308
       requests client auth but user has not loaded client cert/key */
6309
    void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb)
6310
    {
6311
        WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb");
6312
6313
        if (ctx != NULL) {
6314
            ctx->CBClientCert = cb;
6315
        }
6316
    }
6317
#endif
6318
6319
    void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx,
6320
        CertSetupCallback cb, void *arg)
6321
    {
6322
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb");
6323
        if (ctx == NULL)
6324
            return;
6325
6326
        ctx->certSetupCb = cb;
6327
        ctx->certSetupCbArg = arg;
6328
    }
6329
6330
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
6331
            const byte** suites, word16* suiteSz,
6332
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
6333
    {
6334
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
6335
6336
        if (suites != NULL)
6337
            *suites = NULL;
6338
        if (suiteSz != NULL)
6339
            *suiteSz = 0;
6340
        if (hashSigAlgo != NULL)
6341
            *hashSigAlgo = NULL;
6342
        if (hashSigAlgoSz != NULL)
6343
            *hashSigAlgoSz = 0;
6344
6345
        if (ssl != NULL && ssl->clSuites != NULL) {
6346
            if (suites != NULL && suiteSz != NULL) {
6347
                *suites = ssl->clSuites->suites;
6348
                *suiteSz = ssl->clSuites->suiteSz;
6349
            }
6350
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
6351
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
6352
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
6353
            }
6354
            return WOLFSSL_SUCCESS;
6355
        }
6356
        return WOLFSSL_FAILURE;
6357
    }
6358
6359
#ifndef NO_TLS
6360
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
6361
            byte second)
6362
    {
6363
        WOLFSSL_CIPHERSUITE_INFO info;
6364
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
6365
                CipherRequires(first, second, REQUIRES_RSA_SIG));
6366
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
6367
                /* Static ECC ciphers may require RSA for authentication */
6368
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
6369
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
6370
        info.eccStatic =
6371
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
6372
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
6373
        return info;
6374
    }
6375
#endif
6376
6377
    /**
6378
     * @param first First byte of the hash and signature algorithm
6379
     * @param second Second byte of the hash and signature algorithm
6380
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
6381
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
6382
     */
6383
    int wolfSSL_get_sigalg_info(byte first, byte second,
6384
            int* hashAlgo, int* sigAlgo)
6385
    {
6386
        byte input[2];
6387
        byte hashType;
6388
        byte sigType;
6389
6390
        if (hashAlgo == NULL || sigAlgo == NULL)
6391
            return BAD_FUNC_ARG;
6392
6393
        input[0] = first;
6394
        input[1] = second;
6395
        DecodeSigAlg(input, &hashType, &sigType);
6396
6397
        /* cast so that compiler reminds us of unimplemented values */
6398
        switch ((enum SignatureAlgorithm)sigType) {
6399
        case anonymous_sa_algo:
6400
            *sigAlgo = ANONk;
6401
            break;
6402
        case rsa_sa_algo:
6403
            *sigAlgo = RSAk;
6404
            break;
6405
        case dsa_sa_algo:
6406
            *sigAlgo = DSAk;
6407
            break;
6408
        case ecc_dsa_sa_algo:
6409
        case ecc_brainpool_sa_algo:
6410
            *sigAlgo = ECDSAk;
6411
            break;
6412
        case rsa_pss_sa_algo:
6413
            *sigAlgo = RSAPSSk;
6414
            break;
6415
        case ed25519_sa_algo:
6416
            *sigAlgo = ED25519k;
6417
            break;
6418
        case rsa_pss_pss_algo:
6419
            *sigAlgo = RSAPSSk;
6420
            break;
6421
        case ed448_sa_algo:
6422
            *sigAlgo = ED448k;
6423
            break;
6424
        case falcon_level1_sa_algo:
6425
            *sigAlgo = FALCON_LEVEL1k;
6426
            break;
6427
        case falcon_level5_sa_algo:
6428
            *sigAlgo = FALCON_LEVEL5k;
6429
            break;
6430
        case mldsa_44_sa_algo:
6431
            *sigAlgo = ML_DSA_44k;
6432
            break;
6433
        case mldsa_65_sa_algo:
6434
            *sigAlgo = ML_DSA_65k;
6435
            break;
6436
        case mldsa_87_sa_algo:
6437
            *sigAlgo = ML_DSA_87k;
6438
            break;
6439
        case sm2_sa_algo:
6440
            *sigAlgo = SM2k;
6441
            break;
6442
        case invalid_sa_algo:
6443
        case any_sa_algo:
6444
        default:
6445
            *hashAlgo = WC_HASH_TYPE_NONE;
6446
            *sigAlgo = 0;
6447
            return BAD_FUNC_ARG;
6448
        }
6449
6450
        /* cast so that compiler reminds us of unimplemented values */
6451
        switch((enum wc_MACAlgorithm)hashType) {
6452
        case no_mac:
6453
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
6454
            *hashAlgo = WC_HASH_TYPE_NONE;
6455
            break;
6456
        case md5_mac:
6457
            *hashAlgo = WC_HASH_TYPE_MD5;
6458
            break;
6459
        case sha_mac:
6460
            *hashAlgo = WC_HASH_TYPE_SHA;
6461
            break;
6462
        case sha224_mac:
6463
            *hashAlgo = WC_HASH_TYPE_SHA224;
6464
            break;
6465
        case sha256_mac:
6466
            *hashAlgo = WC_HASH_TYPE_SHA256;
6467
            break;
6468
        case sha384_mac:
6469
            *hashAlgo = WC_HASH_TYPE_SHA384;
6470
            break;
6471
        case sha512_mac:
6472
            *hashAlgo = WC_HASH_TYPE_SHA512;
6473
            break;
6474
        case blake2b_mac:
6475
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
6476
            break;
6477
        case sm3_mac:
6478
#ifdef WOLFSSL_SM3
6479
            *hashAlgo = WC_HASH_TYPE_SM3;
6480
#else
6481
            *hashAlgo = WC_HASH_TYPE_NONE;
6482
#endif
6483
            break;
6484
        default:
6485
            *hashAlgo = WC_HASH_TYPE_NONE;
6486
            *sigAlgo = 0;
6487
            return BAD_FUNC_ARG;
6488
        }
6489
        return 0;
6490
    }
6491
6492
    /**
6493
     * Internal wrapper for calling certSetupCb
6494
     * @param ssl The SSL/TLS Object
6495
     * @return 0 on success
6496
     */
6497
    int CertSetupCbWrapper(WOLFSSL* ssl)
6498
    {
6499
        int ret = 0;
6500
        if (ssl->ctx->certSetupCb != NULL) {
6501
            WOLFSSL_MSG("Calling user cert setup callback");
6502
            ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg);
6503
            if (ret == 1) {
6504
                WOLFSSL_MSG("User cert callback returned success");
6505
                ret = 0;
6506
            }
6507
            else if (ret == 0) {
6508
                SendAlert(ssl, alert_fatal, internal_error);
6509
                ret = CLIENT_CERT_CB_ERROR;
6510
            }
6511
            else if (ret < 0) {
6512
                ret = WOLFSSL_ERROR_WANT_X509_LOOKUP;
6513
            }
6514
            else {
6515
                WOLFSSL_MSG("Unexpected user callback return");
6516
                ret = CLIENT_CERT_CB_ERROR;
6517
            }
6518
        }
6519
        return ret;
6520
    }
6521
#endif /* WOLFSSL_CERT_SETUP_CB */
6522
6523
#ifdef OPENSSL_EXTRA
6524
6525
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
6526
        && !defined(WC_NO_RNG)
6527
    static const byte srp_N[] = {
6528
        0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8,
6529
        0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF,
6530
        0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6,
6531
        0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13,
6532
        0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B,
6533
        0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7,
6534
        0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69,
6535
        0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85,
6536
        0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC,
6537
        0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E,
6538
        0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F,
6539
        0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3
6540
    };
6541
    static const byte srp_g[] = {
6542
        0x02
6543
    };
6544
6545
    int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username)
6546
    {
6547
        int r = 0;
6548
        SrpSide srp_side = SRP_CLIENT_SIDE;
6549
6550
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username");
6551
        if (ctx == NULL || ctx->srp == NULL || username==NULL)
6552
            return WOLFSSL_FAILURE;
6553
6554
        if (ctx->method->side == WOLFSSL_SERVER_END){
6555
            srp_side = SRP_SERVER_SIDE;
6556
        } else if (ctx->method->side == WOLFSSL_CLIENT_END){
6557
            srp_side = SRP_CLIENT_SIDE;
6558
        } else {
6559
            WOLFSSL_MSG("Init CTX failed");
6560
            return WOLFSSL_FAILURE;
6561
        }
6562
6563
        if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) {
6564
            WOLFSSL_MSG("Init SRP CTX failed");
6565
            XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
6566
            ctx->srp = NULL;
6567
            return WOLFSSL_FAILURE;
6568
        }
6569
        r = wc_SrpSetUsername(ctx->srp, (const byte*)username,
6570
                              (word32)XSTRLEN(username));
6571
        if (r < 0) {
6572
            WOLFSSL_MSG("fail to set srp username.");
6573
            return WOLFSSL_FAILURE;
6574
        }
6575
6576
        /* if wolfSSL_CTX_set_srp_password has already been called, */
6577
        /* use saved password here */
6578
        if (ctx->srp_password != NULL) {
6579
            if (ctx->srp->user == NULL)
6580
                return WOLFSSL_FAILURE;
6581
            return wolfSSL_CTX_set_srp_password(ctx, (char*)ctx->srp_password);
6582
        }
6583
6584
        return WOLFSSL_SUCCESS;
6585
    }
6586
6587
    int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password)
6588
    {
6589
        int r;
6590
        byte salt[SRP_SALT_SIZE];
6591
6592
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password");
6593
        if (ctx == NULL || ctx->srp == NULL || password == NULL)
6594
            return WOLFSSL_FAILURE;
6595
6596
        if (ctx->srp->user != NULL) {
6597
            WC_RNG rng;
6598
            if (wc_InitRng(&rng) < 0) {
6599
                WOLFSSL_MSG("wc_InitRng failed");
6600
                return WOLFSSL_FAILURE;
6601
            }
6602
            XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
6603
            r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
6604
            wc_FreeRng(&rng);
6605
            if (r <  0) {
6606
                WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
6607
                return WOLFSSL_FAILURE;
6608
            }
6609
            if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
6610
                                srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
6611
                                salt, sizeof(salt)/sizeof(salt[0])) < 0){
6612
                WOLFSSL_MSG("wc_SrpSetParam failed");
6613
                return WOLFSSL_FAILURE;
6614
            }
6615
            r = wc_SrpSetPassword(ctx->srp, (const byte*)password,
6616
                                  (word32)XSTRLEN(password));
6617
            if (r < 0) {
6618
                WOLFSSL_MSG("wc_SrpSetPassword failed.");
6619
                return WOLFSSL_FAILURE;
6620
            }
6621
            XFREE(ctx->srp_password, NULL, DYNAMIC_TYPE_SRP);
6622
            ctx->srp_password = NULL;
6623
        } else {
6624
            /* save password for wolfSSL_set_srp_username */
6625
            XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
6626
6627
            ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap,
6628
                                               DYNAMIC_TYPE_SRP);
6629
            if (ctx->srp_password == NULL){
6630
                WOLFSSL_MSG("memory allocation error");
6631
                return WOLFSSL_FAILURE;
6632
            }
6633
            XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1);
6634
        }
6635
        return WOLFSSL_SUCCESS;
6636
    }
6637
6638
    /**
6639
     * The modulus passed to wc_SrpSetParams in ssl.c is constant so check
6640
     * that the requested strength is less than or equal to the size of the
6641
     * static modulus size.
6642
     * @param ctx Not used
6643
     * @param strength Minimum number of bits for the modulus
6644
     * @return 1 if strength is less than or equal to static modulus
6645
     *         0 if strength is greater than static modulus
6646
     */
6647
    int  wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength)
6648
    {
6649
        (void)ctx;
6650
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength");
6651
        if (strength > (int)(sizeof(srp_N)*8)) {
6652
            WOLFSSL_MSG("Bad Parameter");
6653
            return WOLFSSL_FAILURE;
6654
        }
6655
        return WOLFSSL_SUCCESS;
6656
    }
6657
6658
    char* wolfSSL_get_srp_username(WOLFSSL *ssl)
6659
    {
6660
        if (ssl && ssl->ctx && ssl->ctx->srp) {
6661
            return (char*) ssl->ctx->srp->user;
6662
        }
6663
        return NULL;
6664
    }
6665
    #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */
6666
6667
    /* keyblock size in bytes or -1 */
6668
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
6669
    {
6670
        if (ssl == NULL)
6671
            return WOLFSSL_FATAL_ERROR;
6672
6673
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
6674
                    ssl->specs.hash_size);
6675
    }
6676
6677
#endif /* OPENSSL_EXTRA */
6678
6679
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
6680
    defined(WOLFSSL_WPAS_SMALL)
6681
6682
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
6683
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
6684
                                     unsigned char** sr, unsigned int* srLen,
6685
                                     unsigned char** cr, unsigned int* crLen)
6686
    {
6687
        if (ssl == NULL || ssl->arrays == NULL)
6688
            return WOLFSSL_FATAL_ERROR;
6689
6690
        *ms = ssl->arrays->masterSecret;
6691
        *sr = ssl->arrays->serverRandom;
6692
        *cr = ssl->arrays->clientRandom;
6693
6694
        *msLen = SECRET_LEN;
6695
        *srLen = RAN_LEN;
6696
        *crLen = RAN_LEN;
6697
6698
        return WOLFSSL_SUCCESS;
6699
    }
6700
6701
    void wolfSSL_set_accept_state(WOLFSSL* ssl)
6702
    {
6703
        WOLFSSL_ENTER("wolfSSL_set_accept_state");
6704
6705
        if (ssl == NULL)
6706
            return;
6707
6708
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
6709
    #ifdef HAVE_ECC
6710
            WC_DECLARE_VAR(key, ecc_key, 1, 0);
6711
            word32 idx = 0;
6712
6713
        #ifdef WOLFSSL_SMALL_STACK
6714
            key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
6715
                                    DYNAMIC_TYPE_ECC);
6716
            if (key == NULL) {
6717
                WOLFSSL_MSG("Error allocating memory for ecc_key");
6718
            }
6719
        #endif
6720
            if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) {
6721
                if (wc_ecc_init(key) >= 0) {
6722
                    if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
6723
                            key, ssl->buffers.key->length) != 0) {
6724
                        ssl->options.haveECDSAsig = 0;
6725
                        ssl->options.haveECC = 0;
6726
                        ssl->options.haveStaticECC = 0;
6727
                    }
6728
                    wc_ecc_free(key);
6729
                }
6730
            }
6731
            WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
6732
    #endif
6733
6734
    #ifndef NO_DH
6735
            if (!ssl->options.haveDH && ssl->ctx->haveDH) {
6736
                ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
6737
                ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
6738
                ssl->options.haveDH = 1;
6739
            }
6740
    #endif
6741
        }
6742
6743
        if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
6744
            WOLFSSL_MSG("Error initializing server side");
6745
        }
6746
    }
6747
6748
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
6749
6750
    /* return true if connection established */
6751
    /* this works for TLS and DTLS */
6752
    int wolfSSL_is_init_finished(const WOLFSSL* ssl)
6753
0
    {
6754
0
        if (ssl == NULL)
6755
0
            return 0;
6756
6757
#if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
6758
        if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls
6759
                && IsAtLeastTLSv1_3(ssl->version)) {
6760
            return ssl->options.serverState == SERVER_FINISHED_ACKED;
6761
        }
6762
#endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT */
6763
6764
        /* Can't use ssl->options.connectState and ssl->options.acceptState
6765
         * because they differ in meaning for TLS <=1.2 and 1.3 */
6766
0
        if (ssl->options.handShakeState == HANDSHAKE_DONE)
6767
0
            return 1;
6768
6769
0
        return 0;
6770
0
    }
6771
6772
#ifdef OPENSSL_EXTRA
6773
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
6774
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
6775
    {
6776
        /* wolfSSL verifies all these internally */
6777
        (void)ctx;
6778
        (void)f;
6779
    }
6780
6781
6782
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
6783
    {
6784
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
6785
        if(ssl==NULL) {
6786
            WOLFSSL_MSG("Shutdown not set. ssl is null");
6787
            return;
6788
        }
6789
6790
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
6791
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
6792
    }
6793
#endif
6794
6795
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
6796
0
    {
6797
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
6798
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
6799
0
        if(ctx == NULL)
6800
0
            return BAD_FUNC_ARG;
6801
0
        return (long)ctx->mask;
6802
0
    }
6803
6804
    /* forward declaration */
6805
    static long wolf_set_options(long old_op, long op);
6806
6807
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
6808
0
    {
6809
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
6810
6811
0
        if (ctx == NULL)
6812
0
            return BAD_FUNC_ARG;
6813
6814
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
6815
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
6816
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
6817
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
6818
          ctx->noTicketTls12 = 1;
6819
        }
6820
        /* This code is here for documentation purpose. You must not turn off
6821
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
6822
         * Because we need to support both stateful and stateless tickets.
6823
        #ifdef WOLFSSL_TLS13
6824
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
6825
                ctx->noTicketTls13 = 1;
6826
            }
6827
        #endif
6828
        */
6829
#endif
6830
0
        return (long)ctx->mask;
6831
0
    }
6832
6833
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
6834
0
    {
6835
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
6836
0
        if(ctx == NULL)
6837
0
            return BAD_FUNC_ARG;
6838
0
        ctx->mask &= (unsigned long)~opt;
6839
0
        return (long)ctx->mask;
6840
0
    }
6841
6842
#ifdef OPENSSL_EXTRA
6843
6844
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
6845
    {
6846
        WOLFSSL_ENTER("wolfSSL_set_rfd");
6847
        ssl->rfd = rfd;      /* not used directly to allow IO callbacks */
6848
6849
        ssl->IOCB_ReadCtx  = &ssl->rfd;
6850
6851
    #ifdef WOLFSSL_DTLS
6852
        if (ssl->options.dtls) {
6853
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
6854
            ssl->buffers.dtlsCtx.rfd = rfd;
6855
        #ifdef USE_WOLFSSL_IO
6856
            ssl->buffers.dtlsCtx.rfdIsDGram =
6857
                (byte)(wolfIO_SockIsDGram(rfd) != 0);
6858
        #endif
6859
        }
6860
    #endif
6861
6862
        return WOLFSSL_SUCCESS;
6863
    }
6864
6865
6866
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
6867
    {
6868
        WOLFSSL_ENTER("wolfSSL_set_wfd");
6869
        ssl->wfd = wfd;      /* not used directly to allow IO callbacks */
6870
6871
        ssl->IOCB_WriteCtx  = &ssl->wfd;
6872
6873
        return WOLFSSL_SUCCESS;
6874
    }
6875
#endif /* OPENSSL_EXTRA */
6876
6877
#ifdef WOLFSSL_ENCRYPTED_KEYS
6878
6879
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
6880
                                                   void* userdata)
6881
    {
6882
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
6883
        if (ctx)
6884
            ctx->passwd_userdata = userdata;
6885
    }
6886
6887
6888
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
6889
                                           cb)
6890
    {
6891
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
6892
        if (ctx)
6893
            ctx->passwd_cb = cb;
6894
    }
6895
6896
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
6897
    {
6898
        if (ctx == NULL || ctx->passwd_cb == NULL) {
6899
            return NULL;
6900
        }
6901
6902
        return ctx->passwd_cb;
6903
    }
6904
6905
6906
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
6907
    {
6908
        if (ctx == NULL) {
6909
            return NULL;
6910
        }
6911
6912
        return ctx->passwd_userdata;
6913
    }
6914
6915
#endif /* WOLFSSL_ENCRYPTED_KEYS */
6916
6917
6918
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
6919
    unsigned long wolfSSL_ERR_get_error(void)
6920
    {
6921
        WOLFSSL_ENTER("wolfSSL_ERR_get_error");
6922
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
6923
        return (unsigned long)wc_GetErrorNodeErr();
6924
#else
6925
        return 0;
6926
#endif
6927
    }
6928
#endif
6929
6930
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
6931
6932
    int wolfSSL_num_locks(void)
6933
    {
6934
        return 0;
6935
    }
6936
6937
    void wolfSSL_set_locking_callback(mutex_cb* f)
6938
    {
6939
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
6940
6941
        if (wc_SetMutexCb(f) != 0) {
6942
            WOLFSSL_MSG("Error when setting mutex call back");
6943
        }
6944
    }
6945
6946
    mutex_cb* wolfSSL_get_locking_callback(void)
6947
    {
6948
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
6949
6950
        return wc_GetMutexCb();
6951
    }
6952
6953
6954
    typedef unsigned long (idCb)(void);
6955
    static idCb* inner_idCb = NULL;
6956
6957
    unsigned long wolfSSL_thread_id(void)
6958
    {
6959
        if (inner_idCb != NULL) {
6960
            return inner_idCb();
6961
        }
6962
        else {
6963
            return 0;
6964
        }
6965
    }
6966
6967
6968
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
6969
    {
6970
        inner_idCb = f;
6971
    }
6972
6973
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
6974
#ifndef NO_BIO
6975
    /* print out and clear all errors */
6976
    void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio)
6977
    {
6978
        const char* file = NULL;
6979
        const char* reason = NULL;
6980
        int ret;
6981
        int line = 0;
6982
        char buf[WOLFSSL_MAX_ERROR_SZ * 2];
6983
6984
        WOLFSSL_ENTER("wolfSSL_ERR_print_errors");
6985
6986
        if (bio == NULL) {
6987
            WOLFSSL_MSG("BIO passed in was null");
6988
            return;
6989
        }
6990
6991
        do {
6992
        ret = wc_PeekErrorNode(0, &file, &reason, &line);
6993
        if (ret >= 0) {
6994
            const char* r = wolfSSL_ERR_reason_error_string(
6995
                (unsigned long)(0 - ret));
6996
            if (XSNPRINTF(buf, sizeof(buf),
6997
                          "error:%d:wolfSSL library:%s:%s:%d\n",
6998
                          ret, r, file, line)
6999
                >= (int)sizeof(buf))
7000
            {
7001
                WOLFSSL_MSG("Buffer overrun formatting error message");
7002
            }
7003
            wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf));
7004
            wc_RemoveErrorNode(0);
7005
        }
7006
        } while (ret >= 0);
7007
        if (wolfSSL_BIO_write(bio, "", 1) != 1) {
7008
            WOLFSSL_MSG("Issue writing final string terminator");
7009
        }
7010
    }
7011
#endif /* !NO_BIO */
7012
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
7013
7014
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
7015
7016
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
7017
    defined(HAVE_SECRET_CALLBACK)
7018
#if !defined(NO_WOLFSSL_SERVER)
7019
/* Return the amount of random bytes copied over or error case.
7020
 * ssl : ssl struct after handshake
7021
 * out : buffer to hold random bytes
7022
 * outSz : either 0 (return max buffer sz) or size of out buffer
7023
 */
7024
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
7025
                                                                   size_t outSz)
7026
{
7027
    size_t size;
7028
7029
    /* return max size of buffer */
7030
    if (outSz == 0) {
7031
        return RAN_LEN;
7032
    }
7033
7034
    if (ssl == NULL || out == NULL) {
7035
        return 0;
7036
    }
7037
7038
    if (ssl->arrays == NULL) {
7039
        WOLFSSL_MSG("Arrays struct not saved after handshake");
7040
        return 0;
7041
    }
7042
7043
    if (outSz > RAN_LEN) {
7044
        size = RAN_LEN;
7045
    }
7046
    else {
7047
        size = outSz;
7048
    }
7049
7050
    XMEMCPY(out, ssl->arrays->serverRandom, size);
7051
    return size;
7052
}
7053
#endif /* !NO_WOLFSSL_SERVER */
7054
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
7055
7056
#ifdef OPENSSL_EXTRA
7057
#if !defined(NO_WOLFSSL_SERVER)
7058
/* Used to get the peer ephemeral public key sent during the connection
7059
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
7060
 *       before the ephemeral key is stored.
7061
 * return WOLFSSL_SUCCESS on success */
7062
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
7063
{
7064
    WOLFSSL_EVP_PKEY* ret = NULL;
7065
7066
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
7067
7068
    if (ssl == NULL || pkey == NULL) {
7069
        WOLFSSL_MSG("Bad argument passed in");
7070
        return WOLFSSL_FAILURE;
7071
    }
7072
7073
#ifdef HAVE_ECC
7074
    if (ssl->peerEccKey != NULL) {
7075
        unsigned char* der;
7076
        const unsigned char* pt;
7077
        unsigned int   derSz = 0;
7078
        int sz;
7079
7080
        PRIVATE_KEY_UNLOCK();
7081
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
7082
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
7083
        {
7084
            WOLFSSL_MSG("get ecc der size failed");
7085
            PRIVATE_KEY_LOCK();
7086
            return WOLFSSL_FAILURE;
7087
        }
7088
        PRIVATE_KEY_LOCK();
7089
7090
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
7091
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
7092
        if (der == NULL) {
7093
            WOLFSSL_MSG("Memory error");
7094
            return WOLFSSL_FAILURE;
7095
        }
7096
7097
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
7098
            WOLFSSL_MSG("get ecc der failed");
7099
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
7100
            return WOLFSSL_FAILURE;
7101
        }
7102
        pt = der; /* in case pointer gets advanced */
7103
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
7104
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
7105
    }
7106
#endif
7107
7108
    *pkey = ret;
7109
#ifdef HAVE_ECC
7110
    if (ret != NULL)
7111
        return WOLFSSL_SUCCESS;
7112
    else
7113
#endif
7114
        return WOLFSSL_FAILURE;
7115
}
7116
7117
#endif /* !NO_WOLFSSL_SERVER */
7118
7119
/**
7120
 * This function checks if any compiled in protocol versions are
7121
 * left enabled after calls to set_min or set_max API.
7122
 * @param major The SSL/TLS major version
7123
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7124
 *         protocol versions are left enabled.
7125
 */
7126
static int CheckSslMethodVersion(byte major, unsigned long options)
7127
{
7128
    int sanityConfirmed = 0;
7129
7130
    (void)options;
7131
7132
    switch (major) {
7133
    #ifndef NO_TLS
7134
        case SSLv3_MAJOR:
7135
            #ifdef WOLFSSL_ALLOW_SSLV3
7136
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
7137
                    sanityConfirmed = 1;
7138
                }
7139
            #endif
7140
            #ifndef NO_OLD_TLS
7141
                if (!(options & WOLFSSL_OP_NO_TLSv1))
7142
                    sanityConfirmed = 1;
7143
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
7144
                    sanityConfirmed = 1;
7145
            #endif
7146
            #ifndef WOLFSSL_NO_TLS12
7147
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
7148
                    sanityConfirmed = 1;
7149
            #endif
7150
            #ifdef WOLFSSL_TLS13
7151
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
7152
                    sanityConfirmed = 1;
7153
            #endif
7154
            break;
7155
    #endif
7156
    #ifdef WOLFSSL_DTLS
7157
        case DTLS_MAJOR:
7158
            sanityConfirmed = 1;
7159
            break;
7160
    #endif
7161
        default:
7162
            WOLFSSL_MSG("Invalid major version");
7163
            return WOLFSSL_FAILURE;
7164
    }
7165
    if (!sanityConfirmed) {
7166
        WOLFSSL_MSG("All compiled in TLS versions disabled");
7167
        return WOLFSSL_FAILURE;
7168
    }
7169
    return WOLFSSL_SUCCESS;
7170
}
7171
7172
/**
7173
 * protoVerTbl holds (D)TLS version numbers in ascending order.
7174
 * Except DTLS versions, the newer version is located in the latter part of
7175
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
7176
 * wolfSSL_CTX_set_max_proto_version.
7177
 */
7178
static const int protoVerTbl[] = {
7179
    SSL3_VERSION,
7180
    TLS1_VERSION,
7181
    TLS1_1_VERSION,
7182
    TLS1_2_VERSION,
7183
    TLS1_3_VERSION,
7184
    DTLS1_VERSION,
7185
    DTLS1_2_VERSION
7186
};
7187
/* number of protocol versions listed in protoVerTbl */
7188
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
7189
7190
/**
7191
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
7192
 * version to use by SSL objects created from this WOLFSSL_CTX.
7193
 * This API guarantees that a version of SSL/TLS lower than specified
7194
 * here will not be allowed. If the version specified is not compiled in
7195
 * then this API sets the lowest compiled in protocol version.
7196
 * This API also accept 0 as version, to set the minimum version automatically.
7197
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
7198
 * are enabled.
7199
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
7200
 * @param version Any of the following
7201
 *          * 0
7202
 *          * SSL3_VERSION
7203
 *          * TLS1_VERSION
7204
 *          * TLS1_1_VERSION
7205
 *          * TLS1_2_VERSION
7206
 *          * TLS1_3_VERSION
7207
 *          * DTLS1_VERSION
7208
 *          * DTLS1_2_VERSION
7209
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7210
 *         protocol versions are left enabled.
7211
 */
7212
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
7213
{
7214
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
7215
7216
    if (ctx == NULL) {
7217
        return WOLFSSL_FAILURE;
7218
    }
7219
7220
    switch (version) {
7221
#ifndef NO_TLS
7222
        case SSL3_VERSION:
7223
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
7224
            ctx->minDowngrade = SSLv3_MINOR;
7225
            break;
7226
#endif
7227
        case TLS1_VERSION:
7228
        #ifdef WOLFSSL_ALLOW_TLSV10
7229
            ctx->minDowngrade = TLSv1_MINOR;
7230
            break;
7231
        #endif
7232
        case TLS1_1_VERSION:
7233
        #ifndef NO_OLD_TLS
7234
            ctx->minDowngrade = TLSv1_1_MINOR;
7235
            break;
7236
        #endif
7237
        case TLS1_2_VERSION:
7238
        #ifndef WOLFSSL_NO_TLS12
7239
            ctx->minDowngrade = TLSv1_2_MINOR;
7240
            break;
7241
        #endif
7242
        case TLS1_3_VERSION:
7243
        #ifdef WOLFSSL_TLS13
7244
            ctx->minDowngrade = TLSv1_3_MINOR;
7245
            break;
7246
        #endif
7247
#endif
7248
#ifdef WOLFSSL_DTLS
7249
        case DTLS1_VERSION:
7250
    #ifndef NO_OLD_TLS
7251
            ctx->minDowngrade = DTLS_MINOR;
7252
            break;
7253
    #endif
7254
        case DTLS1_2_VERSION:
7255
            ctx->minDowngrade = DTLSv1_2_MINOR;
7256
            break;
7257
#endif
7258
        default:
7259
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7260
            return WOLFSSL_FAILURE;
7261
    }
7262
7263
    switch (version) {
7264
#ifndef NO_TLS
7265
    case TLS1_3_VERSION:
7266
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
7267
        FALL_THROUGH;
7268
    case TLS1_2_VERSION:
7269
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
7270
        FALL_THROUGH;
7271
    case TLS1_1_VERSION:
7272
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
7273
        FALL_THROUGH;
7274
    case TLS1_VERSION:
7275
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
7276
        break;
7277
    case SSL3_VERSION:
7278
    case SSL2_VERSION:
7279
        /* Nothing to do here */
7280
        break;
7281
#endif
7282
#ifdef WOLFSSL_DTLS
7283
    case DTLS1_VERSION:
7284
    case DTLS1_2_VERSION:
7285
        break;
7286
#endif
7287
    default:
7288
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7289
        return WOLFSSL_FAILURE;
7290
    }
7291
7292
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
7293
}
7294
7295
/* Sets the min protocol version allowed with WOLFSSL_CTX
7296
 * returns WOLFSSL_SUCCESS on success */
7297
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
7298
{
7299
    int ret;
7300
    int proto    = 0;
7301
    int maxProto = 0;
7302
    int i;
7303
    int idx = 0;
7304
7305
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
7306
7307
    if (ctx == NULL) {
7308
        return WOLFSSL_FAILURE;
7309
    }
7310
7311
    if (version != 0) {
7312
        proto = version;
7313
        ctx->minProto = 0; /* turn min proto flag off */
7314
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7315
            if (protoVerTbl[i] == version) {
7316
                break;
7317
            }
7318
        }
7319
    }
7320
    else {
7321
        /* when 0 is specified as version, try to find out the min version */
7322
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7323
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
7324
            if (ret == WOLFSSL_SUCCESS) {
7325
                proto = protoVerTbl[i];
7326
                ctx->minProto = 1; /* turn min proto flag on */
7327
                break;
7328
            }
7329
        }
7330
    }
7331
7332
    /* check case where max > min , if so then clear the NO_* options
7333
     * i is the index into the table for proto version used, see if the max
7334
     * proto version index found is smaller */
7335
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
7336
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
7337
        if (protoVerTbl[idx] == maxProto) {
7338
            break;
7339
        }
7340
    }
7341
    if (idx < i) {
7342
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
7343
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
7344
                WOLFSSL_OP_NO_TLSv1_3);
7345
    }
7346
7347
    ret = Set_CTX_min_proto_version(ctx, proto);
7348
    return ret;
7349
}
7350
7351
/**
7352
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
7353
 * version to use by SSL objects created from this WOLFSSL_CTX.
7354
 * This API guarantees that a version of SSL/TLS higher than specified
7355
 * here will not be allowed. If the version specified is not compiled in
7356
 * then this API sets the highest compiled in protocol version.
7357
 * This API also accept 0 as version, to set the maximum version automatically.
7358
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
7359
 * are enabled.
7360
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
7361
 * @param ver Any of the following
7362
 *          * 0
7363
 *          * SSL3_VERSION
7364
 *          * TLS1_VERSION
7365
 *          * TLS1_1_VERSION
7366
 *          * TLS1_2_VERSION
7367
 *          * TLS1_3_VERSION
7368
 *          * DTLS1_VERSION
7369
 *          * DTLS1_2_VERSION
7370
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
7371
 *         protocol versions are left enabled.
7372
 */
7373
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
7374
{
7375
    int ret;
7376
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
7377
7378
    if (!ctx || !ctx->method) {
7379
        WOLFSSL_MSG("Bad parameter");
7380
        return WOLFSSL_FAILURE;
7381
    }
7382
7383
    switch (ver) {
7384
#ifndef NO_TLS
7385
#ifndef NO_OLD_TLS
7386
    case SSL2_VERSION:
7387
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
7388
        return WOLFSSL_FAILURE;
7389
#endif
7390
    case SSL3_VERSION:
7391
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
7392
        FALL_THROUGH;
7393
    case TLS1_VERSION:
7394
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
7395
        FALL_THROUGH;
7396
    case TLS1_1_VERSION:
7397
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
7398
        FALL_THROUGH;
7399
    case TLS1_2_VERSION:
7400
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
7401
        FALL_THROUGH;
7402
    case TLS1_3_VERSION:
7403
        /* Nothing to do here */
7404
        break;
7405
#endif
7406
#ifdef WOLFSSL_DTLS
7407
    case DTLS1_VERSION:
7408
    case DTLS1_2_VERSION:
7409
        break;
7410
#endif
7411
    default:
7412
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7413
        return WOLFSSL_FAILURE;
7414
    }
7415
7416
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
7417
    if (ret == WOLFSSL_SUCCESS) {
7418
        /* Check the major */
7419
        switch (ver) {
7420
    #ifndef NO_TLS
7421
        case SSL3_VERSION:
7422
        case TLS1_VERSION:
7423
        case TLS1_1_VERSION:
7424
        case TLS1_2_VERSION:
7425
        case TLS1_3_VERSION:
7426
            if (ctx->method->version.major != SSLv3_MAJOR) {
7427
                WOLFSSL_MSG("Mismatched protocol version");
7428
                return WOLFSSL_FAILURE;
7429
            }
7430
            break;
7431
    #endif
7432
    #ifdef WOLFSSL_DTLS
7433
        case DTLS1_VERSION:
7434
        case DTLS1_2_VERSION:
7435
            if (ctx->method->version.major != DTLS_MAJOR) {
7436
                WOLFSSL_MSG("Mismatched protocol version");
7437
                return WOLFSSL_FAILURE;
7438
            }
7439
            break;
7440
    #endif
7441
        }
7442
        /* Update the method */
7443
        switch (ver) {
7444
    #ifndef NO_TLS
7445
        case SSL3_VERSION:
7446
            ctx->method->version.minor = SSLv3_MINOR;
7447
            break;
7448
        case TLS1_VERSION:
7449
            ctx->method->version.minor = TLSv1_MINOR;
7450
            break;
7451
        case TLS1_1_VERSION:
7452
            ctx->method->version.minor = TLSv1_1_MINOR;
7453
            break;
7454
        case TLS1_2_VERSION:
7455
            ctx->method->version.minor = TLSv1_2_MINOR;
7456
            break;
7457
        case TLS1_3_VERSION:
7458
            ctx->method->version.minor = TLSv1_3_MINOR;
7459
            break;
7460
    #endif
7461
    #ifdef WOLFSSL_DTLS
7462
        case DTLS1_VERSION:
7463
            ctx->method->version.minor = DTLS_MINOR;
7464
            break;
7465
        case DTLS1_2_VERSION:
7466
            ctx->method->version.minor = DTLSv1_2_MINOR;
7467
            break;
7468
    #endif
7469
        default:
7470
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7471
            return WOLFSSL_FAILURE;
7472
        }
7473
    }
7474
    return ret;
7475
}
7476
7477
7478
/* Sets the max protocol version allowed with WOLFSSL_CTX
7479
 * returns WOLFSSL_SUCCESS on success */
7480
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
7481
{
7482
    int i;
7483
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
7484
    int minProto;
7485
7486
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
7487
7488
    if (ctx == NULL) {
7489
        return ret;
7490
    }
7491
7492
    /* clear out flags and reset min protocol version */
7493
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
7494
    wolfSSL_CTX_clear_options(ctx,
7495
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
7496
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
7497
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
7498
    if (version != 0) {
7499
        ctx->maxProto = 0; /* turn max proto flag off */
7500
        return Set_CTX_max_proto_version(ctx, version);
7501
    }
7502
7503
    /* when 0 is specified as version, try to find out the min version from
7504
     * the bottom to top of the protoverTbl.
7505
     */
7506
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
7507
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
7508
        if (ret == WOLFSSL_SUCCESS) {
7509
            ctx->maxProto = 1; /* turn max proto flag on */
7510
            break;
7511
        }
7512
    }
7513
7514
    return ret;
7515
}
7516
7517
7518
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
7519
{
7520
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
7521
7522
    if (ssl == NULL) {
7523
        return WOLFSSL_FAILURE;
7524
    }
7525
7526
    switch (ver) {
7527
#ifndef NO_TLS
7528
        case SSL3_VERSION:
7529
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
7530
            ssl->options.minDowngrade = SSLv3_MINOR;
7531
            break;
7532
#endif
7533
        case TLS1_VERSION:
7534
        #ifdef WOLFSSL_ALLOW_TLSV10
7535
            ssl->options.minDowngrade = TLSv1_MINOR;
7536
            break;
7537
        #endif
7538
        case TLS1_1_VERSION:
7539
        #ifndef NO_OLD_TLS
7540
            ssl->options.minDowngrade = TLSv1_1_MINOR;
7541
            break;
7542
        #endif
7543
        case TLS1_2_VERSION:
7544
        #ifndef WOLFSSL_NO_TLS12
7545
            ssl->options.minDowngrade = TLSv1_2_MINOR;
7546
            break;
7547
        #endif
7548
        case TLS1_3_VERSION:
7549
        #ifdef WOLFSSL_TLS13
7550
            ssl->options.minDowngrade = TLSv1_3_MINOR;
7551
            break;
7552
        #endif
7553
#endif
7554
#ifdef WOLFSSL_DTLS
7555
        case DTLS1_VERSION:
7556
    #ifndef NO_OLD_TLS
7557
            ssl->options.minDowngrade = DTLS_MINOR;
7558
            break;
7559
    #endif
7560
        case DTLS1_2_VERSION:
7561
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
7562
            break;
7563
#endif
7564
        default:
7565
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7566
            return WOLFSSL_FAILURE;
7567
    }
7568
7569
    switch (ver) {
7570
#ifndef NO_TLS
7571
    case TLS1_3_VERSION:
7572
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
7573
        FALL_THROUGH;
7574
    case TLS1_2_VERSION:
7575
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
7576
        FALL_THROUGH;
7577
    case TLS1_1_VERSION:
7578
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
7579
        FALL_THROUGH;
7580
    case TLS1_VERSION:
7581
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
7582
        break;
7583
    case SSL3_VERSION:
7584
    case SSL2_VERSION:
7585
        /* Nothing to do here */
7586
        break;
7587
#endif
7588
#ifdef WOLFSSL_DTLS
7589
    case DTLS1_VERSION:
7590
    case DTLS1_2_VERSION:
7591
        break;
7592
#endif
7593
    default:
7594
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7595
        return WOLFSSL_FAILURE;
7596
    }
7597
7598
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
7599
}
7600
7601
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
7602
{
7603
    int i;
7604
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
7605
7606
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
7607
7608
    if (ssl == NULL) {
7609
        return WOLFSSL_FAILURE;
7610
    }
7611
    if (version != 0) {
7612
        return Set_SSL_min_proto_version(ssl, version);
7613
    }
7614
7615
    /* when 0 is specified as version, try to find out the min version */
7616
    for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
7617
        ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
7618
        if (ret == WOLFSSL_SUCCESS)
7619
            break;
7620
    }
7621
7622
    return ret;
7623
}
7624
7625
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
7626
{
7627
7628
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
7629
7630
    if (!ssl) {
7631
        WOLFSSL_MSG("Bad parameter");
7632
        return WOLFSSL_FAILURE;
7633
    }
7634
7635
    switch (ver) {
7636
    case SSL2_VERSION:
7637
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
7638
        return WOLFSSL_FAILURE;
7639
#ifndef NO_TLS
7640
    case SSL3_VERSION:
7641
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
7642
        FALL_THROUGH;
7643
    case TLS1_VERSION:
7644
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
7645
        FALL_THROUGH;
7646
    case TLS1_1_VERSION:
7647
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
7648
        FALL_THROUGH;
7649
    case TLS1_2_VERSION:
7650
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
7651
        FALL_THROUGH;
7652
    case TLS1_3_VERSION:
7653
        /* Nothing to do here */
7654
        break;
7655
#endif
7656
#ifdef WOLFSSL_DTLS
7657
    case DTLS1_VERSION:
7658
    case DTLS1_2_VERSION:
7659
        break;
7660
#endif
7661
    default:
7662
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
7663
        return WOLFSSL_FAILURE;
7664
    }
7665
7666
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
7667
}
7668
7669
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
7670
{
7671
    int i;
7672
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
7673
7674
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
7675
7676
    if (ssl == NULL) {
7677
        return WOLFSSL_FAILURE;
7678
    }
7679
    if (version != 0) {
7680
        return Set_SSL_max_proto_version(ssl, version);
7681
    }
7682
7683
    /* when 0 is specified as version, try to find out the min version from
7684
     * the bottom to top of the protoverTbl.
7685
     */
7686
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
7687
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
7688
        if (ret == WOLFSSL_SUCCESS)
7689
            break;
7690
    }
7691
7692
    return ret;
7693
}
7694
7695
static int GetMinProtoVersion(int minDowngrade)
7696
{
7697
    int ret;
7698
7699
    switch (minDowngrade) {
7700
#ifndef NO_OLD_TLS
7701
    #ifdef WOLFSSL_ALLOW_SSLV3
7702
        case SSLv3_MINOR:
7703
            ret = SSL3_VERSION;
7704
            break;
7705
    #endif
7706
    #ifdef WOLFSSL_ALLOW_TLSV10
7707
        case TLSv1_MINOR:
7708
            ret = TLS1_VERSION;
7709
            break;
7710
    #endif
7711
        case TLSv1_1_MINOR:
7712
            ret = TLS1_1_VERSION;
7713
            break;
7714
#endif
7715
#ifndef WOLFSSL_NO_TLS12
7716
        case TLSv1_2_MINOR:
7717
            ret = TLS1_2_VERSION;
7718
            break;
7719
#endif
7720
#ifdef WOLFSSL_TLS13
7721
        case TLSv1_3_MINOR:
7722
            ret = TLS1_3_VERSION;
7723
            break;
7724
#endif
7725
        default:
7726
            ret = 0;
7727
            break;
7728
    }
7729
7730
    return ret;
7731
}
7732
7733
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
7734
{
7735
    int ret = 0;
7736
7737
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
7738
7739
    if (ctx != NULL) {
7740
        if (ctx->minProto) {
7741
            ret = 0;
7742
        }
7743
        else {
7744
            ret = GetMinProtoVersion(ctx->minDowngrade);
7745
        }
7746
    }
7747
    else {
7748
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
7749
    }
7750
7751
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
7752
7753
    return ret;
7754
}
7755
7756
7757
/* returns the maximum allowed protocol version given the 'options' used
7758
 * returns WOLFSSL_FATAL_ERROR on no match */
7759
static int GetMaxProtoVersion(long options)
7760
{
7761
#ifndef NO_TLS
7762
#ifdef WOLFSSL_TLS13
7763
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
7764
        return TLS1_3_VERSION;
7765
#endif
7766
#ifndef WOLFSSL_NO_TLS12
7767
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
7768
        return TLS1_2_VERSION;
7769
#endif
7770
#ifndef NO_OLD_TLS
7771
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
7772
        return TLS1_1_VERSION;
7773
    #ifdef WOLFSSL_ALLOW_TLSV10
7774
    if (!(options & WOLFSSL_OP_NO_TLSv1))
7775
        return TLS1_VERSION;
7776
    #endif
7777
    #ifdef WOLFSSL_ALLOW_SSLV3
7778
    if (!(options & WOLFSSL_OP_NO_SSLv3))
7779
        return SSL3_VERSION;
7780
    #endif
7781
#endif
7782
#else
7783
    (void)options;
7784
#endif /* NO_TLS */
7785
    return WOLFSSL_FATAL_ERROR;
7786
}
7787
7788
7789
/* returns the maximum protocol version for 'ctx' */
7790
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
7791
{
7792
    int ret = 0;
7793
    long options = 0; /* default to nothing set */
7794
7795
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
7796
7797
    if (ctx != NULL) {
7798
        options = wolfSSL_CTX_get_options(ctx);
7799
    }
7800
7801
    if ((ctx != NULL) && ctx->maxProto) {
7802
        ret = 0;
7803
    }
7804
    else {
7805
        ret = GetMaxProtoVersion(options);
7806
    }
7807
7808
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
7809
7810
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
7811
        WOLFSSL_MSG("Error getting max proto version");
7812
        ret = 0; /* setting ret to 0 to match compat return */
7813
    }
7814
    return ret;
7815
}
7816
#endif /* OPENSSL_EXTRA */
7817
7818
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
7819
    defined(HAVE_SECRET_CALLBACK)
7820
#if !defined(NO_WOLFSSL_CLIENT)
7821
/* Return the amount of random bytes copied over or error case.
7822
 * ssl : ssl struct after handshake
7823
 * out : buffer to hold random bytes
7824
 * outSz : either 0 (return max buffer sz) or size of out buffer
7825
 */
7826
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
7827
                                                                   size_t outSz)
7828
{
7829
    size_t size;
7830
7831
    /* return max size of buffer */
7832
    if (outSz == 0) {
7833
        return RAN_LEN;
7834
    }
7835
7836
    if (ssl == NULL || out == NULL) {
7837
        return 0;
7838
    }
7839
7840
    if (ssl->arrays == NULL) {
7841
        WOLFSSL_MSG("Arrays struct not saved after handshake");
7842
        return 0;
7843
    }
7844
7845
    if (outSz > RAN_LEN) {
7846
        size = RAN_LEN;
7847
    }
7848
    else {
7849
        size = outSz;
7850
    }
7851
7852
    XMEMCPY(out, ssl->arrays->clientRandom, size);
7853
    return size;
7854
}
7855
#endif /* !NO_WOLFSSL_CLIENT */
7856
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
7857
7858
#ifdef OPENSSL_EXTRA
7859
7860
    unsigned long wolfSSLeay(void)
7861
    {
7862
#ifdef SSLEAY_VERSION_NUMBER
7863
        return SSLEAY_VERSION_NUMBER;
7864
#else
7865
        return OPENSSL_VERSION_NUMBER;
7866
#endif
7867
    }
7868
7869
    unsigned long wolfSSL_OpenSSL_version_num(void)
7870
    {
7871
        return OPENSSL_VERSION_NUMBER;
7872
    }
7873
7874
    const char* wolfSSLeay_version(int type)
7875
    {
7876
        (void)type;
7877
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
7878
        return wolfSSL_OpenSSL_version(type);
7879
#else
7880
        return wolfSSL_OpenSSL_version();
7881
#endif
7882
    }
7883
#endif /* OPENSSL_EXTRA */
7884
7885
#ifdef OPENSSL_EXTRA
7886
    void wolfSSL_ERR_free_strings(void)
7887
    {
7888
        /* handled internally */
7889
    }
7890
7891
    void wolfSSL_cleanup_all_ex_data(void)
7892
    {
7893
        /* nothing to do here */
7894
    }
7895
7896
#endif /* OPENSSL_EXTRA */
7897
7898
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
7899
    defined(HAVE_CURL)
7900
    void wolfSSL_ERR_clear_error(void)
7901
    {
7902
        WOLFSSL_ENTER("wolfSSL_ERR_clear_error");
7903
    #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
7904
        wc_ClearErrorNodes();
7905
    #endif
7906
    }
7907
#endif
7908
7909
    int wolfSSL_clear(WOLFSSL* ssl)
7910
0
    {
7911
0
        WOLFSSL_ENTER("wolfSSL_clear");
7912
7913
0
        if (ssl == NULL) {
7914
0
            return WOLFSSL_FAILURE;
7915
0
        }
7916
7917
0
        if (!ssl->options.handShakeDone) {
7918
            /* Only reset the session if we didn't complete a handshake */
7919
0
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
7920
0
            ssl->session = wolfSSL_NewSession(ssl->heap);
7921
0
            if (ssl->session == NULL) {
7922
0
                return WOLFSSL_FAILURE;
7923
0
            }
7924
0
        }
7925
7926
        /* reset error */
7927
0
        ssl->error = 0;
7928
7929
        /* reset option bits */
7930
0
        ssl->options.isClosed = 0;
7931
0
        ssl->options.connReset = 0;
7932
0
        ssl->options.sentNotify = 0;
7933
0
        ssl->options.closeNotify = 0;
7934
0
        ssl->options.sendVerify = 0;
7935
0
        ssl->options.serverState = NULL_STATE;
7936
0
        ssl->options.clientState = NULL_STATE;
7937
0
        ssl->options.connectState = CONNECT_BEGIN;
7938
0
        ssl->options.acceptState  = ACCEPT_BEGIN;
7939
0
        ssl->options.handShakeState  = NULL_STATE;
7940
0
        ssl->options.handShakeDone = 0;
7941
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
7942
        /* A per-certificate yield (WOLFSSL_ASYNC_CERT_YIELD) sets this and it is
7943
         * normally cleared on the next ProcessPeerCerts re-entry. Clear it here
7944
         * so reusing this object after abandoning a yielded handshake cannot
7945
         * skip the ProcessPeerCerts state reset on the next fresh entry. */
7946
        ssl->options.certYieldPending = 0;
7947
#endif
7948
0
        ssl->recordSzOverhead = 0;
7949
0
        ssl->options.processReply = 0; /* doProcessInit */
7950
0
        ssl->options.havePeerVerify = 0;
7951
0
        ssl->options.havePeerCert = 0;
7952
0
        ssl->options.peerAuthGood = 0;
7953
0
        ssl->options.tls1_3 = 0;
7954
0
        ssl->options.haveSessionId = 0;
7955
0
        ssl->options.tls = 0;
7956
0
        ssl->options.tls1_1 = 0;
7957
0
    #ifdef WOLFSSL_TLS13
7958
    #ifdef WOLFSSL_SEND_HRR_COOKIE
7959
        ssl->options.hrrSentCookie = 0;
7960
    #endif
7961
0
        ssl->options.hrrSentKeyShare = 0;
7962
0
    #endif
7963
    #ifdef WOLFSSL_DTLS
7964
        ssl->options.dtlsStateful = 0;
7965
    #endif
7966
0
    #ifdef WOLFSSL_TLS13
7967
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
7968
        ssl->options.noPskDheKe = ssl->ctx->noPskDheKe;
7969
        #ifdef HAVE_SUPPORTED_CURVES
7970
        ssl->options.onlyPskDheKe = ssl->ctx->onlyPskDheKe;
7971
        #endif
7972
    #endif
7973
0
    #endif
7974
    #ifdef HAVE_SESSION_TICKET
7975
        #ifdef WOLFSSL_TLS13
7976
        ssl->options.ticketsSent = 0;
7977
        #endif
7978
        ssl->options.rejectTicket = 0;
7979
    #endif
7980
    #ifdef WOLFSSL_EARLY_DATA
7981
        ssl->earlyData = no_early_data;
7982
        ssl->earlyDataSz = 0;
7983
    #endif
7984
7985
0
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
7986
0
        TLSX_FreeAll(ssl->extensions, ssl->heap);
7987
0
        ssl->extensions = NULL;
7988
0
      #if defined(HAVE_SECURE_RENEGOTIATION) \
7989
0
       || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7990
0
        ssl->secure_renegotiation = NULL;
7991
0
      #endif
7992
0
    #endif
7993
7994
0
        if (ssl->keys.encryptionOn) {
7995
0
            ForceZero(ssl->buffers.inputBuffer.buffer -
7996
0
                ssl->buffers.inputBuffer.offset,
7997
0
                ssl->buffers.inputBuffer.bufferSize);
7998
        #ifdef WOLFSSL_CHECK_MEM_ZERO
7999
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
8000
                ssl->buffers.inputBuffer.offset,
8001
                ssl->buffers.inputBuffer.bufferSize);
8002
        #endif
8003
0
        }
8004
0
        ssl->keys.encryptionOn = 0;
8005
0
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
8006
8007
        /* Discard any partial handshake-message reassembly on reuse. */
8008
0
        XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
8009
0
        ssl->pendingMsg = NULL;
8010
0
        ssl->pendingMsgSz = 0;
8011
0
        ssl->pendingMsgOffset = 0;
8012
0
        ssl->pendingMsgType = 0;
8013
8014
0
        FreeCiphers(ssl);
8015
0
        InitCiphers(ssl);
8016
0
        InitCipherSpecs(&ssl->specs);
8017
8018
0
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
8019
0
            return WOLFSSL_FAILURE;
8020
8021
0
        if (InitHandshakeHashes(ssl) != 0)
8022
0
            return WOLFSSL_FAILURE;
8023
8024
#ifdef KEEP_PEER_CERT
8025
        FreeX509(&ssl->peerCert);
8026
        InitX509(&ssl->peerCert, 0, ssl->heap);
8027
#endif
8028
8029
#ifdef WOLFSSL_QUIC
8030
        wolfSSL_quic_clear(ssl);
8031
#endif
8032
#ifdef HAVE_OCSP
8033
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
8034
        ssl->response_idx = 0;
8035
#endif
8036
#endif
8037
0
        return WOLFSSL_SUCCESS;
8038
0
    }
8039
8040
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
8041
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
8042
    {
8043
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
8044
8045
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
8046
        switch(mode) {
8047
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
8048
                ctx->partialWrite = 1;
8049
                break;
8050
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8051
            case SSL_MODE_RELEASE_BUFFERS:
8052
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
8053
                break;
8054
            #endif
8055
            case WOLFSSL_MODE_AUTO_RETRY:
8056
                ctx->autoRetry = 1;
8057
                break;
8058
            default:
8059
                WOLFSSL_MSG("Mode Not Implemented");
8060
        }
8061
8062
        /* WOLFSSL_MODE_AUTO_RETRY
8063
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
8064
8065
        return mode;
8066
    }
8067
8068
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
8069
    {
8070
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
8071
8072
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
8073
        switch(mode) {
8074
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
8075
                ctx->partialWrite = 0;
8076
                break;
8077
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8078
            case SSL_MODE_RELEASE_BUFFERS:
8079
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
8080
                break;
8081
            #endif
8082
            case WOLFSSL_MODE_AUTO_RETRY:
8083
                ctx->autoRetry = 0;
8084
                break;
8085
            default:
8086
                WOLFSSL_MSG("Mode Not Implemented");
8087
        }
8088
8089
        /* WOLFSSL_MODE_AUTO_RETRY
8090
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
8091
8092
        return 0;
8093
    }
8094
#endif
8095
8096
#ifdef OPENSSL_EXTRA
8097
8098
    #ifndef NO_WOLFSSL_STUB
8099
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
8100
    {
8101
        /* TODO: */
8102
        (void)ssl;
8103
        WOLFSSL_STUB("SSL_get_mode");
8104
        return 0;
8105
    }
8106
    #endif
8107
8108
    #ifndef NO_WOLFSSL_STUB
8109
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
8110
    {
8111
        /* TODO: */
8112
        (void)ctx;
8113
        WOLFSSL_STUB("SSL_CTX_get_mode");
8114
        return 0;
8115
    }
8116
    #endif
8117
8118
    #ifndef NO_WOLFSSL_STUB
8119
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
8120
    {
8121
        /* TODO: maybe? */
8122
        (void)ctx;
8123
        (void)m;
8124
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
8125
    }
8126
    #endif
8127
8128
8129
    /* returns the unsigned error value and increments the pointer into the
8130
     * error queue.
8131
     *
8132
     * file  pointer to file name
8133
     * line  gets set to line number of error when not NULL
8134
     */
8135
    unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line)
8136
    {
8137
    #ifdef WOLFSSL_HAVE_ERROR_QUEUE
8138
        int ret = wc_PullErrorNode(file, NULL, line);
8139
        if (ret < 0) {
8140
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
8141
                return 0; /* no errors in queue */
8142
            WOLFSSL_MSG("Issue getting error node");
8143
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret);
8144
            ret = 0 - ret; /* return absolute value of error */
8145
8146
            /* panic and try to clear out nodes */
8147
            wc_ClearErrorNodes();
8148
        }
8149
        return (unsigned long)ret;
8150
    #else
8151
        (void)file;
8152
        (void)line;
8153
8154
        return 0;
8155
    #endif
8156
    }
8157
8158
8159
#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \
8160
    (!defined(_WIN32) && !defined(NO_ERROR_QUEUE))
8161
    static const char WOLFSSL_SYS_ACCEPT_T[]  = "accept";
8162
    static const char WOLFSSL_SYS_BIND_T[]    = "bind";
8163
    static const char WOLFSSL_SYS_CONNECT_T[] = "connect";
8164
    static const char WOLFSSL_SYS_FOPEN_T[]   = "fopen";
8165
    static const char WOLFSSL_SYS_FREAD_T[]   = "fread";
8166
    static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo";
8167
    static const char WOLFSSL_SYS_GETSOCKOPT_T[]  = "getsockopt";
8168
    static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname";
8169
    static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname";
8170
    static const char WOLFSSL_SYS_GETNAMEINFO_T[]   = "getnameinfo";
8171
    static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname";
8172
    static const char WOLFSSL_SYS_IOCTLSOCKET_T[]   = "ioctlsocket";
8173
    static const char WOLFSSL_SYS_LISTEN_T[]        = "listen";
8174
    static const char WOLFSSL_SYS_OPENDIR_T[]       = "opendir";
8175
    static const char WOLFSSL_SYS_SETSOCKOPT_T[]    = "setsockopt";
8176
    static const char WOLFSSL_SYS_SOCKET_T[]        = "socket";
8177
8178
    /* switch with int mapped to function name for compatibility */
8179
    static const char* wolfSSL_ERR_sys_func(int fun)
8180
    {
8181
        switch (fun) {
8182
            case WOLFSSL_SYS_ACCEPT:      return WOLFSSL_SYS_ACCEPT_T;
8183
            case WOLFSSL_SYS_BIND:        return WOLFSSL_SYS_BIND_T;
8184
            case WOLFSSL_SYS_CONNECT:     return WOLFSSL_SYS_CONNECT_T;
8185
            case WOLFSSL_SYS_FOPEN:       return WOLFSSL_SYS_FOPEN_T;
8186
            case WOLFSSL_SYS_FREAD:       return WOLFSSL_SYS_FREAD_T;
8187
            case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T;
8188
            case WOLFSSL_SYS_GETSOCKOPT:  return WOLFSSL_SYS_GETSOCKOPT_T;
8189
            case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T;
8190
            case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T;
8191
            case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T;
8192
            case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T;
8193
            case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T;
8194
            case WOLFSSL_SYS_LISTEN:      return WOLFSSL_SYS_LISTEN_T;
8195
            case WOLFSSL_SYS_OPENDIR:     return WOLFSSL_SYS_OPENDIR_T;
8196
            case WOLFSSL_SYS_SETSOCKOPT:  return WOLFSSL_SYS_SETSOCKOPT_T;
8197
            case WOLFSSL_SYS_SOCKET:      return WOLFSSL_SYS_SOCKET_T;
8198
            default:
8199
                return "NULL";
8200
        }
8201
    }
8202
#endif /* DEBUG_WOLFSSL */
8203
8204
8205
    void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file,
8206
            int line)
8207
    {
8208
        WOLFSSL_ENTER("wolfSSL_ERR_put_error");
8209
8210
        #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA)
8211
        (void)fun;
8212
        (void)err;
8213
        (void)file;
8214
        (void)line;
8215
        WOLFSSL_MSG("Not compiled in debug mode");
8216
        #elif defined(OPENSSL_EXTRA) && \
8217
                (defined(_WIN32) || defined(NO_ERROR_QUEUE))
8218
        (void)fun;
8219
        (void)file;
8220
        (void)line;
8221
        WOLFSSL_ERROR(err);
8222
        #else
8223
        WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line,
8224
            file, NULL);
8225
        #endif
8226
        (void)lib;
8227
    }
8228
8229
8230
    /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for
8231
     * more flexibility.
8232
     *
8233
     * file  output pointer to file where error happened
8234
     * line  output to line number of error
8235
     * data  output data. Is a string if WOLFSSL_ERR_TXT_STRING flag is used
8236
     * flags output format of output
8237
     *
8238
     * Returns the error value or 0 if no errors are in the queue
8239
     */
8240
    unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line,
8241
                                                  const char** data, int *flags)
8242
    {
8243
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
8244
        int ret;
8245
8246
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
8247
8248
        if (flags != NULL)
8249
            *flags = WOLFSSL_ERR_TXT_STRING; /* Clear the flags */
8250
8251
        ret = wc_PullErrorNode(file, data, line);
8252
        if (ret < 0) {
8253
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
8254
                return 0; /* no errors in queue */
8255
            WOLFSSL_MSG("Error with pulling error node!");
8256
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret);
8257
            ret = 0 - ret; /* return absolute value of error */
8258
8259
            /* panic and try to clear out nodes */
8260
            wc_ClearErrorNodes();
8261
        }
8262
8263
        return (unsigned long)ret;
8264
#else
8265
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
8266
        WOLFSSL_MSG("Error queue turned off, can not get error line");
8267
        (void)file;
8268
        (void)line;
8269
        (void)data;
8270
        (void)flags;
8271
        return 0;
8272
#endif
8273
    }
8274
8275
#endif /* OPENSSL_EXTRA */
8276
8277
8278
#ifdef SESSION_CERTS
8279
    /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object.
8280
     *
8281
     * x509  WOLFSSL_X509 object to decode into.
8282
     * in    X509 DER data.
8283
     * len   Length of the X509 DER data.
8284
     * returns the new certificate on success, otherwise NULL.
8285
     */
8286
    static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len)
8287
    {
8288
        int          ret;
8289
        WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
8290
        if (x509 == NULL || in == NULL || len <= 0)
8291
            return BAD_FUNC_ARG;
8292
8293
        WC_ALLOC_VAR_EX(cert, DecodedCert, 1, NULL, DYNAMIC_TYPE_DCERT,
8294
            return MEMORY_E);
8295
8296
        /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object.
8297
         */
8298
        InitDecodedCert(cert, (byte*)in, (word32)len, NULL);
8299
        if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) == 0) {
8300
        /* Check if x509 was not previously initialized by wolfSSL_X509_new() */
8301
            if (x509->dynamicMemory != TRUE)
8302
                InitX509(x509, 0, NULL);
8303
            ret = CopyDecodedToX509(x509, cert);
8304
        }
8305
        FreeDecodedCert(cert);
8306
        WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
8307
8308
        return ret;
8309
    }
8310
#endif /* SESSION_CERTS */
8311
8312
8313
#ifdef KEEP_PEER_CERT
8314
    WOLFSSL_ABI
8315
    WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl)
8316
    {
8317
        WOLFSSL_X509* ret = NULL;
8318
        WOLFSSL_ENTER("wolfSSL_get_peer_certificate");
8319
        if (ssl != NULL) {
8320
            if (ssl->peerCert.issuer.sz)
8321
                ret = wolfSSL_X509_dup(&ssl->peerCert);
8322
#ifdef SESSION_CERTS
8323
            else if (ssl->session->chain.count > 0) {
8324
                if (DecodeToX509(&ssl->peerCert,
8325
                        ssl->session->chain.certs[0].buffer,
8326
                        ssl->session->chain.certs[0].length) == 0) {
8327
                    ret = wolfSSL_X509_dup(&ssl->peerCert);
8328
                }
8329
            }
8330
#endif
8331
        }
8332
        WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL);
8333
        return ret;
8334
    }
8335
8336
#endif /* KEEP_PEER_CERT */
8337
8338
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
8339
/* Return stack of peer certs.
8340
 * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl
8341
 * is.
8342
 */
8343
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl)
8344
{
8345
    WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain");
8346
8347
    if (ssl == NULL)
8348
        return NULL;
8349
8350
    /* Try to populate if NULL or empty */
8351
    if (ssl->peerCertChain == NULL ||
8352
            wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) {
8353
        wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl);
8354
    }
8355
    return ssl->peerCertChain;
8356
}
8357
8358
8359
static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
8360
        WOLFSSL_X509 *x);
8361
/**
8362
 * Recursively push the issuer CA chain onto the stack
8363
 * @param cm The cert manager that is queried for the issuer
8364
 * @param x  This cert's issuer will be queried in cm
8365
 * @param sk The issuer is pushed onto this stack
8366
 * @return 0 on success or no issuer found
8367
 *         WOLFSSL_FATAL_ERROR on a fatal error
8368
 */
8369
static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm,
8370
        WOLFSSL_X509 *x, WOLFSSL_STACK* sk)
8371
{
8372
    int i;
8373
    for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
8374
        WOLFSSL_X509* issuer = NULL;
8375
        if (x509GetIssuerFromCM(&issuer, cm, x) != WOLFSSL_SUCCESS)
8376
            break;
8377
        if (wolfSSL_sk_X509_push(sk, issuer) <= 0) {
8378
            wolfSSL_X509_free(issuer);
8379
            issuer = NULL;
8380
            return WOLFSSL_FATAL_ERROR;
8381
        }
8382
        x = issuer;
8383
    }
8384
    return 0;
8385
}
8386
8387
8388
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
8389
    or ssl->verifiedChain based off of the ssl session chain. Attempts to place
8390
    CA certificates at the bottom of the stack for a verified chain. Returns
8391
    stack of WOLFSSL_X509 certs or NULL on failure */
8392
static WOLF_STACK_OF(WOLFSSL_X509)* CreatePeerCertChain(const WOLFSSL* ssl,
8393
    int verifiedFlag)
8394
{
8395
    WOLFSSL_STACK* sk;
8396
    WOLFSSL_X509* x509;
8397
    int i = 0;
8398
    int err;
8399
8400
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
8401
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
8402
        return NULL;
8403
8404
    sk = wolfSSL_sk_X509_new_null();
8405
    for (i = 0; i < ssl->session->chain.count; i++) {
8406
        x509 = wolfSSL_X509_new_ex(ssl->heap);
8407
        if (x509 == NULL) {
8408
            WOLFSSL_MSG("Error Creating X509");
8409
            wolfSSL_sk_X509_pop_free(sk, NULL);
8410
            return NULL;
8411
        }
8412
        err = DecodeToX509(x509, ssl->session->chain.certs[i].buffer,
8413
                             ssl->session->chain.certs[i].length);
8414
        if (err == 0 && wolfSSL_sk_X509_push(sk, x509) <= 0)
8415
            err = WOLFSSL_FATAL_ERROR;
8416
        if (err == 0 && i == ssl->session->chain.count-1 && verifiedFlag) {
8417
            /* On the last element in the verified chain try to add the CA chain
8418
             * if we have one for this cert */
8419
            SSL_CM_WARNING(ssl);
8420
            err = PushCAx509Chain(SSL_CM(ssl), x509, sk);
8421
        }
8422
        if (err != 0) {
8423
            WOLFSSL_MSG("Error decoding cert");
8424
            wolfSSL_X509_free(x509);
8425
            x509 = NULL;
8426
            wolfSSL_sk_X509_pop_free(sk, NULL);
8427
            return NULL;
8428
        }
8429
    }
8430
8431
    if (sk == NULL) {
8432
        WOLFSSL_MSG("Null session chain");
8433
    }
8434
    return sk;
8435
}
8436
8437
8438
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
8439
    returns the stack on success and NULL on failure */
8440
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl)
8441
{
8442
    WOLFSSL_STACK* sk;
8443
8444
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
8445
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
8446
        return NULL;
8447
8448
    sk = CreatePeerCertChain(ssl, 0);
8449
8450
    if (sk != NULL) {
8451
        if (ssl->options.side == WOLFSSL_SERVER_END) {
8452
            if (ssl->session->peer)
8453
                wolfSSL_X509_free(ssl->session->peer);
8454
8455
            ssl->session->peer = wolfSSL_sk_X509_shift(sk);
8456
            ssl->session->peerVerifyRet = ssl->peerVerifyRet;
8457
        }
8458
        if (ssl->peerCertChain != NULL)
8459
            wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
8460
        /* This is Free'd when ssl is Free'd */
8461
        ssl->peerCertChain = sk;
8462
    }
8463
    return sk;
8464
}
8465
8466
#ifdef KEEP_PEER_CERT
8467
/**
8468
 * Implemented in a similar way that ngx_ssl_ocsp_validate does it when
8469
 * SSL_get0_verified_chain is not available.
8470
 * @param ssl WOLFSSL object to extract certs from
8471
 * @return Stack of verified certs
8472
 */
8473
WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl)
8474
{
8475
    WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL;
8476
    WOLFSSL_X509_STORE_CTX* storeCtx = NULL;
8477
    WOLFSSL_X509* peerCert = NULL;
8478
8479
    WOLFSSL_ENTER("wolfSSL_get0_verified_chain");
8480
8481
    if (ssl == NULL || ssl->ctx == NULL) {
8482
        WOLFSSL_MSG("Bad parameter");
8483
        return NULL;
8484
    }
8485
8486
    peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl);
8487
    if (peerCert == NULL) {
8488
        WOLFSSL_MSG("wolfSSL_get_peer_certificate error");
8489
        return NULL;
8490
    }
8491
    /* wolfSSL_get_peer_certificate returns a copy. We want the internal
8492
     * member so that we don't have to worry about free'ing it. We call
8493
     * wolfSSL_get_peer_certificate so that we don't have to worry about
8494
     * setting up the internal pointer. */
8495
    wolfSSL_X509_free(peerCert);
8496
    peerCert = (WOLFSSL_X509*)&ssl->peerCert;
8497
    chain = CreatePeerCertChain((WOLFSSL*)ssl, 1);
8498
    if (chain == NULL) {
8499
        WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error");
8500
        return NULL;
8501
    }
8502
8503
    if (ssl->verifiedChain != NULL) {
8504
        wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL);
8505
    }
8506
    ((WOLFSSL*)ssl)->verifiedChain = chain;
8507
8508
    storeCtx = wolfSSL_X509_STORE_CTX_new();
8509
    if (storeCtx == NULL) {
8510
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error");
8511
        return NULL;
8512
    }
8513
    if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl),
8514
            peerCert, chain) != WOLFSSL_SUCCESS) {
8515
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error");
8516
        wolfSSL_X509_STORE_CTX_free(storeCtx);
8517
        return NULL;
8518
    }
8519
    if (wolfSSL_X509_verify_cert(storeCtx) <= 0) {
8520
        WOLFSSL_MSG("wolfSSL_X509_verify_cert error");
8521
        wolfSSL_X509_STORE_CTX_free(storeCtx);
8522
        return NULL;
8523
    }
8524
    wolfSSL_X509_STORE_CTX_free(storeCtx);
8525
    return chain;
8526
}
8527
#endif /* KEEP_PEER_CERT */
8528
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
8529
8530
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8531
void wolfSSL_set_connect_state(WOLFSSL* ssl)
8532
{
8533
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
8534
    if (ssl == NULL) {
8535
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
8536
        return;
8537
    }
8538
8539
    #ifndef NO_DH
8540
    /* client creates its own DH parameters on handshake */
8541
    if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
8542
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
8543
            DYNAMIC_TYPE_PUBLIC_KEY);
8544
    }
8545
    ssl->buffers.serverDH_P.buffer = NULL;
8546
    if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
8547
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
8548
            DYNAMIC_TYPE_PUBLIC_KEY);
8549
    }
8550
    ssl->buffers.serverDH_G.buffer = NULL;
8551
    #endif
8552
8553
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
8554
        WOLFSSL_MSG("Error initializing client side");
8555
    }
8556
}
8557
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
8558
8559
8560
int wolfSSL_get_shutdown(const WOLFSSL* ssl)
8561
0
{
8562
0
    int isShutdown = 0;
8563
8564
0
    WOLFSSL_ENTER("wolfSSL_get_shutdown");
8565
8566
0
    if (ssl) {
8567
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8568
        if (ssl->options.shutdownDone) {
8569
            /* The SSL object was possibly cleared with wolfSSL_clear after
8570
             * a successful shutdown. Simulate a response for a full
8571
             * bidirectional shutdown. */
8572
            isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN;
8573
        }
8574
        else
8575
#endif
8576
0
        {
8577
            /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent   *
8578
             * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */
8579
0
            if (ssl->options.sentNotify)
8580
0
                isShutdown |= WOLFSSL_SENT_SHUTDOWN;
8581
0
            if (ssl->options.closeNotify||ssl->options.connReset)
8582
0
                isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN;
8583
0
        }
8584
8585
0
    }
8586
8587
0
    WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown);
8588
0
    return isShutdown;
8589
0
}
8590
8591
8592
int wolfSSL_session_reused(WOLFSSL* ssl)
8593
0
{
8594
0
    int resuming = 0;
8595
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
8596
0
    if (ssl) {
8597
0
#ifndef HAVE_SECURE_RENEGOTIATION
8598
0
        resuming = ssl->options.resuming;
8599
#else
8600
        resuming = ssl->options.resuming || ssl->options.resumed;
8601
#endif
8602
0
    }
8603
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
8604
0
    return resuming;
8605
0
}
8606
8607
/* helper function that takes in a protocol version struct and returns string */
8608
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
8609
0
{
8610
0
    WOLFSSL_ENTER("wolfSSL_get_version");
8611
8612
0
    if (version == NULL) {
8613
0
        return "Bad arg";
8614
0
    }
8615
8616
0
    if (version->major == SSLv3_MAJOR) {
8617
0
        switch (version->minor) {
8618
0
            case SSLv3_MINOR :
8619
0
                return "SSLv3";
8620
0
            case TLSv1_MINOR :
8621
0
                return "TLSv1";
8622
0
            case TLSv1_1_MINOR :
8623
0
                return "TLSv1.1";
8624
0
            case TLSv1_2_MINOR :
8625
0
                return "TLSv1.2";
8626
0
            case TLSv1_3_MINOR :
8627
0
                return "TLSv1.3";
8628
0
            default:
8629
0
                return "unknown";
8630
0
        }
8631
0
    }
8632
#ifdef WOLFSSL_DTLS
8633
    else if (version->major == DTLS_MAJOR) {
8634
        switch (version->minor) {
8635
            case DTLS_MINOR :
8636
                return "DTLS";
8637
            case DTLSv1_2_MINOR :
8638
                return "DTLSv1.2";
8639
            case DTLSv1_3_MINOR :
8640
                return "DTLSv1.3";
8641
            default:
8642
                return "unknown";
8643
        }
8644
    }
8645
#endif /* WOLFSSL_DTLS */
8646
0
    return "unknown";
8647
0
}
8648
8649
8650
const char* wolfSSL_get_version(const WOLFSSL* ssl)
8651
0
{
8652
0
    if (ssl == NULL) {
8653
0
        WOLFSSL_MSG("Bad argument");
8654
0
        return "unknown";
8655
0
    }
8656
8657
0
    return wolfSSL_internal_get_version(&ssl->version);
8658
0
}
8659
8660
8661
/* current library version */
8662
const char* wolfSSL_lib_version(void)
8663
0
{
8664
0
    return LIBWOLFSSL_VERSION_STRING;
8665
0
}
8666
8667
#ifdef OPENSSL_EXTRA
8668
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
8669
const char* wolfSSL_OpenSSL_version(int a)
8670
{
8671
    (void)a;
8672
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
8673
}
8674
#else
8675
const char* wolfSSL_OpenSSL_version(void)
8676
{
8677
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
8678
}
8679
#endif /* WOLFSSL_QT */
8680
#endif
8681
8682
8683
/* current library version in hex */
8684
word32 wolfSSL_lib_version_hex(void)
8685
0
{
8686
0
    return LIBWOLFSSL_VERSION_HEX;
8687
0
}
8688
8689
8690
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
8691
0
{
8692
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
8693
0
    if (ssl)
8694
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
8695
0
    return 0;
8696
0
}
8697
8698
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
8699
0
{
8700
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
8701
0
    if (ssl) {
8702
0
        ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
8703
0
        ssl->cipher.cipherSuite  = ssl->options.cipherSuite;
8704
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8705
        ssl->cipher.bits = ssl->specs.key_size * 8;
8706
#endif
8707
0
        return &ssl->cipher;
8708
0
    }
8709
0
    else
8710
0
        return NULL;
8711
0
}
8712
8713
8714
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
8715
0
{
8716
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
8717
8718
0
    if (cipher == NULL) {
8719
0
        return NULL;
8720
0
    }
8721
8722
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
8723
0
        !defined(WOLFSSL_QT)
8724
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
8725
    #else
8726
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
8727
                cipher->cipherSuite);
8728
    #endif
8729
0
}
8730
8731
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
8732
0
{
8733
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
8734
8735
0
    if (cipher == NULL || cipher->ssl == NULL) {
8736
0
        return NULL;
8737
0
    }
8738
8739
0
    return wolfSSL_get_version(cipher->ssl);
8740
0
}
8741
8742
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
8743
0
{
8744
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
8745
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
8746
0
}
8747
8748
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
8749
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
8750
0
{
8751
    /* get access to cipher_name_idx in internal.c */
8752
0
    return wolfSSL_get_cipher_name_internal(ssl);
8753
0
}
8754
8755
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
8756
    byte cipherSuite)
8757
0
{
8758
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
8759
0
}
8760
8761
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
8762
        byte cipherSuite)
8763
0
{
8764
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
8765
0
}
8766
8767
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
8768
0
                                       byte* cipherSuite, int *flags) {
8769
0
    if ((name == NULL) ||
8770
0
        (cipherSuite0 == NULL) ||
8771
0
        (cipherSuite == NULL) ||
8772
0
        (flags == NULL))
8773
0
        return BAD_FUNC_ARG;
8774
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
8775
0
                                  flags);
8776
0
}
8777
8778
8779
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
8780
0
{
8781
0
    word16 cipher_id = 0;
8782
8783
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
8784
8785
0
    if (cipher && cipher->ssl) {
8786
0
        cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) |
8787
0
                     cipher->ssl->options.cipherSuite;
8788
0
    }
8789
8790
0
    return cipher_id;
8791
0
}
8792
8793
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
8794
0
{
8795
0
    const WOLFSSL_CIPHER* cipher = NULL;
8796
0
    byte cipherSuite0, cipherSuite;
8797
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
8798
8799
    /* extract cipher id information */
8800
0
    cipherSuite =   (value       & 0xFF);
8801
0
    cipherSuite0 = ((value >> 8) & 0xFF);
8802
8803
    /* TODO: lookup by cipherSuite0 / cipherSuite */
8804
0
    (void)cipherSuite0;
8805
0
    (void)cipherSuite;
8806
8807
0
    return cipher;
8808
0
}
8809
8810
8811
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
8812
    !defined(NO_DH) || (defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM))
8813
#ifdef HAVE_FFDHE
8814
static const char* wolfssl_ffdhe_name(word16 group)
8815
0
{
8816
0
    const char* str = NULL;
8817
0
    switch (group) {
8818
0
        case WOLFSSL_FFDHE_2048:
8819
0
            str = "FFDHE_2048";
8820
0
            break;
8821
0
        case WOLFSSL_FFDHE_3072:
8822
0
            str = "FFDHE_3072";
8823
0
            break;
8824
0
        case WOLFSSL_FFDHE_4096:
8825
0
            str = "FFDHE_4096";
8826
0
            break;
8827
0
        case WOLFSSL_FFDHE_6144:
8828
0
            str = "FFDHE_6144";
8829
0
            break;
8830
0
        case WOLFSSL_FFDHE_8192:
8831
0
            str = "FFDHE_8192";
8832
0
            break;
8833
0
        default:
8834
0
            break;
8835
0
    }
8836
0
    return str;
8837
0
}
8838
#endif
8839
/* Return the name of the curve used for key exchange as a printable string.
8840
 *
8841
 * ssl  The SSL/TLS object.
8842
 * returns NULL if ECDH was not used, otherwise the name as a string.
8843
 */
8844
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
8845
0
{
8846
0
    const char* cName = NULL;
8847
8848
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
8849
8850
0
    if (ssl == NULL)
8851
0
        return NULL;
8852
8853
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
8854
    /* Check for post-quantum groups. Return now because we do not want the ECC
8855
     * check to override this result in the case of a hybrid. */
8856
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
8857
0
        switch (ssl->namedGroup) {
8858
0
#ifndef WOLFSSL_NO_ML_KEM
8859
0
    #ifndef WOLFSSL_NO_ML_KEM_512
8860
0
        case WOLFSSL_ML_KEM_512:
8861
0
            return "ML_KEM_512";
8862
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8863
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8864
        case WOLFSSL_P256_ML_KEM_512_OLD:
8865
            return "P256_ML_KEM_512_OLD";
8866
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8867
        case WOLFSSL_SECP256R1MLKEM512:
8868
            return "SecP256r1MLKEM512";
8869
        #ifdef HAVE_CURVE25519
8870
        case WOLFSSL_X25519MLKEM512:
8871
            return "X25519MLKEM512";
8872
        #endif /* HAVE_CURVE25519 */
8873
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8874
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
8875
0
    #ifndef WOLFSSL_NO_ML_KEM_768
8876
0
        case WOLFSSL_ML_KEM_768:
8877
0
            return "ML_KEM_768";
8878
0
        #ifdef WOLFSSL_PQC_HYBRIDS
8879
0
        case WOLFSSL_SECP256R1MLKEM768:
8880
0
            return "SecP256r1MLKEM768";
8881
0
        #ifdef HAVE_CURVE25519
8882
0
        case WOLFSSL_X25519MLKEM768:
8883
0
            return "X25519MLKEM768";
8884
0
        #endif
8885
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
8886
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8887
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8888
        case WOLFSSL_P384_ML_KEM_768_OLD:
8889
            return "P384_ML_KEM_768_OLD";
8890
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8891
        case WOLFSSL_SECP384R1MLKEM768:
8892
            return "SecP384r1MLKEM768";
8893
        #ifdef HAVE_CURVE448
8894
        case WOLFSSL_X448MLKEM768:
8895
            return "X448MLKEM768";
8896
        #endif /* HAVE_CURVE448 */
8897
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8898
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
8899
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
8900
0
        case WOLFSSL_ML_KEM_1024:
8901
0
            return "ML_KEM_1024";
8902
0
        #ifdef WOLFSSL_PQC_HYBRIDS
8903
0
        case WOLFSSL_SECP384R1MLKEM1024:
8904
0
            return "SecP384r1MLKEM1024";
8905
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
8906
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
8907
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
8908
        case WOLFSSL_P521_ML_KEM_1024_OLD:
8909
            return "P521_ML_KEM_1024_OLD";
8910
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
8911
        case WOLFSSL_SECP521R1MLKEM1024:
8912
            return "SecP521r1MLKEM1024";
8913
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
8914
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
8915
0
#endif /* WOLFSSL_NO_ML_KEM */
8916
#ifdef WOLFSSL_MLKEM_KYBER
8917
    #ifndef WOLFSSL_NO_KYBER512
8918
        case WOLFSSL_KYBER_LEVEL1:
8919
            return "KYBER_LEVEL1";
8920
        case WOLFSSL_P256_KYBER_LEVEL1:
8921
            return "P256_KYBER_LEVEL1";
8922
        #ifdef HAVE_CURVE25519
8923
        case WOLFSSL_X25519_KYBER_LEVEL1:
8924
            return "X25519_KYBER_LEVEL1";
8925
        #endif
8926
    #endif
8927
    #ifndef WOLFSSL_NO_KYBER768
8928
        case WOLFSSL_KYBER_LEVEL3:
8929
            return "KYBER_LEVEL3";
8930
        case WOLFSSL_P384_KYBER_LEVEL3:
8931
            return "P384_KYBER_LEVEL3";
8932
        case WOLFSSL_P256_KYBER_LEVEL3:
8933
            return "P256_KYBER_LEVEL3";
8934
        #ifdef HAVE_CURVE25519
8935
        case WOLFSSL_X25519_KYBER_LEVEL3:
8936
            return "X25519_KYBER_LEVEL3";
8937
        #endif
8938
        #ifdef HAVE_CURVE448
8939
        case WOLFSSL_X448_KYBER_LEVEL3:
8940
            return "X448_KYBER_LEVEL3";
8941
        #endif
8942
    #endif
8943
    #ifndef WOLFSSL_NO_KYBER1024
8944
        case WOLFSSL_KYBER_LEVEL5:
8945
            return "KYBER_LEVEL5";
8946
        case WOLFSSL_P521_KYBER_LEVEL5:
8947
            return "P521_KYBER_LEVEL5";
8948
    #endif
8949
#endif /* WOLFSSL_MLKEM_KYBER */
8950
0
        }
8951
0
    }
8952
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
8953
8954
0
#ifdef HAVE_FFDHE
8955
0
    if (ssl->namedGroup != 0) {
8956
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
8957
0
    }
8958
0
#endif
8959
8960
0
#ifdef HAVE_CURVE25519
8961
0
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
8962
0
        cName = "X25519";
8963
0
    }
8964
0
#endif
8965
8966
0
#ifdef HAVE_CURVE448
8967
0
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
8968
0
        cName = "X448";
8969
0
    }
8970
0
#endif
8971
8972
0
#ifdef HAVE_ECC
8973
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
8974
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
8975
0
                                NULL));
8976
0
    }
8977
0
#endif
8978
8979
0
    return cName;
8980
0
}
8981
#endif
8982
8983
#ifdef OPENSSL_EXTRA
8984
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8985
/* return authentication NID corresponding to cipher suite
8986
 * @param cipher a pointer to WOLFSSL_CIPHER
8987
 * return NID if found, WC_NID_undef if not found
8988
 */
8989
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
8990
{
8991
    static const struct authnid {
8992
        const char* alg_name;
8993
        const int  nid;
8994
    } authnid_tbl[] = {
8995
        {"RSA",     WC_NID_auth_rsa},
8996
        {"PSK",     WC_NID_auth_psk},
8997
        {"SRP",     WC_NID_auth_srp},
8998
        {"ECDSA",   WC_NID_auth_ecdsa},
8999
        {"None",    WC_NID_auth_null},
9000
        {NULL,      WC_NID_undef}
9001
    };
9002
9003
    const char* authStr;
9004
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9005
9006
    if (GetCipherSegment(cipher, n) == NULL) {
9007
        WOLFSSL_MSG("no suitable cipher name found");
9008
        return WC_NID_undef;
9009
    }
9010
9011
    authStr = GetCipherAuthStr(n);
9012
9013
    if (authStr != NULL) {
9014
        const struct authnid* sa;
9015
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
9016
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
9017
                return sa->nid;
9018
            }
9019
        }
9020
    }
9021
9022
    return WC_NID_undef;
9023
}
9024
/* return cipher NID corresponding to cipher suite
9025
 * @param cipher a pointer to WOLFSSL_CIPHER
9026
 * return NID if found, WC_NID_undef if not found
9027
 */
9028
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
9029
{
9030
    static const struct ciphernid {
9031
        const char* alg_name;
9032
        const int  nid;
9033
    } ciphernid_tbl[] = {
9034
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
9035
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
9036
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
9037
        {"AES(128)",                WC_NID_aes_128_cbc},
9038
        {"AES(256)",                WC_NID_aes_256_cbc},
9039
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
9040
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
9041
        {"RC4",                     WC_NID_rc4},
9042
        {"3DES",                    WC_NID_des_ede3_cbc},
9043
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
9044
        {"None",                    WC_NID_undef},
9045
        {NULL,                      WC_NID_undef}
9046
    };
9047
9048
    const char* encStr;
9049
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9050
9051
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
9052
9053
    if (GetCipherSegment(cipher, n) == NULL) {
9054
        WOLFSSL_MSG("no suitable cipher name found");
9055
        return WC_NID_undef;
9056
    }
9057
9058
    encStr = GetCipherEncStr(n);
9059
9060
    if (encStr != NULL) {
9061
        const struct ciphernid* c;
9062
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
9063
            if (XSTRCMP(c->alg_name, encStr) == 0) {
9064
                return c->nid;
9065
            }
9066
        }
9067
    }
9068
9069
    return WC_NID_undef;
9070
}
9071
/* return digest NID corresponding to cipher suite
9072
 * @param cipher a pointer to WOLFSSL_CIPHER
9073
 * return NID if found, WC_NID_undef if not found
9074
 */
9075
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
9076
{
9077
    static const struct macnid {
9078
        const char* alg_name;
9079
        const int  nid;
9080
    } macnid_tbl[] = {
9081
        {"SHA1",    WC_NID_sha1},
9082
        {"SHA256",  WC_NID_sha256},
9083
        {"SHA384",  WC_NID_sha384},
9084
        {NULL,      WC_NID_undef}
9085
    };
9086
9087
    const char* name;
9088
    const char* macStr;
9089
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9090
    (void)name;
9091
9092
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
9093
9094
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
9095
        WOLFSSL_MSG("no suitable cipher name found");
9096
        return WC_NID_undef;
9097
    }
9098
9099
    /* in MD5 case, NID will be WC_NID_md5 */
9100
    if (XSTRSTR(name, "MD5") != NULL) {
9101
        return WC_NID_md5;
9102
    }
9103
9104
    macStr = GetCipherMacStr(n);
9105
9106
    if (macStr != NULL) {
9107
        const struct macnid* mc;
9108
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
9109
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
9110
                return mc->nid;
9111
            }
9112
        }
9113
    }
9114
9115
    return WC_NID_undef;
9116
}
9117
/* return key exchange NID corresponding to cipher suite
9118
 * @param cipher a pointer to WOLFSSL_CIPHER
9119
 * return NID if found, WC_NID_undef if not found
9120
 */
9121
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
9122
{
9123
    static const struct kxnid {
9124
        const char* name;
9125
        const int  nid;
9126
    } kxnid_table[] = {
9127
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
9128
        {"ECDH",      WC_NID_kx_ecdhe},
9129
        {"DHEPSK",    WC_NID_kx_dhe_psk},
9130
        {"DH",        WC_NID_kx_dhe},
9131
        {"RSAPSK",    WC_NID_kx_rsa_psk},
9132
        {"SRP",       WC_NID_kx_srp},
9133
        {"EDH",       WC_NID_kx_dhe},
9134
        {"PSK",       WC_NID_kx_psk},
9135
        {"RSA",       WC_NID_kx_rsa},
9136
        {NULL,        WC_NID_undef}
9137
    };
9138
9139
    const char* keaStr;
9140
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9141
9142
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
9143
9144
    if (GetCipherSegment(cipher, n) == NULL) {
9145
        WOLFSSL_MSG("no suitable cipher name found");
9146
        return WC_NID_undef;
9147
    }
9148
9149
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
9150
    if (XSTRCMP(n[0], "TLS13") == 0) {
9151
        return WC_NID_kx_any;
9152
    }
9153
9154
    keaStr = GetCipherKeaStr(n);
9155
9156
    if (keaStr != NULL) {
9157
        const struct kxnid* k;
9158
        for(k = kxnid_table; k->name != NULL; k++) {
9159
            if (XSTRCMP(k->name, keaStr) == 0) {
9160
                return k->nid;
9161
            }
9162
        }
9163
    }
9164
9165
    return WC_NID_undef;
9166
}
9167
/* check if cipher suite is AEAD
9168
 * @param cipher a pointer to WOLFSSL_CIPHER
9169
 * return 1 if cipher is AEAD, 0 otherwise
9170
 */
9171
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
9172
{
9173
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9174
9175
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
9176
9177
    if (GetCipherSegment(cipher, n) == NULL) {
9178
        WOLFSSL_MSG("no suitable cipher name found");
9179
        return WC_NID_undef;
9180
    }
9181
9182
    return IsCipherAEAD(n);
9183
}
9184
/* Creates cipher->description based on cipher->offset
9185
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
9186
 * to a stack of ciphers.
9187
 * @param [in] cipher: A cipher from a stack of ciphers.
9188
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
9189
 */
9190
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
9191
{
9192
    int strLen;
9193
    unsigned long offset;
9194
    char* dp;
9195
    const char* name;
9196
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
9197
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
9198
    int len = MAX_DESCRIPTION_SZ-1;
9199
    const CipherSuiteInfo* cipher_names;
9200
    ProtocolVersion pv;
9201
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
9202
9203
    if (cipher == NULL)
9204
        return WOLFSSL_FAILURE;
9205
9206
    dp = cipher->description;
9207
    if (dp == NULL)
9208
        return WOLFSSL_FAILURE;
9209
9210
    cipher_names = GetCipherNames();
9211
9212
    offset = cipher->offset;
9213
    if (offset >= (unsigned long)GetCipherNamesSize())
9214
        return WOLFSSL_FAILURE;
9215
    pv.major = cipher_names[offset].major;
9216
    pv.minor = cipher_names[offset].minor;
9217
    protocol = wolfSSL_internal_get_version(&pv);
9218
9219
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
9220
        WOLFSSL_MSG("no suitable cipher name found");
9221
        return WOLFSSL_FAILURE;
9222
    }
9223
9224
    /* keaStr */
9225
    keaStr = GetCipherKeaStr(n);
9226
    /* authStr */
9227
    authStr = GetCipherAuthStr(n);
9228
    /* encStr */
9229
    encStr = GetCipherEncStr(n);
9230
    if ((cipher->bits = SetCipherBits(encStr)) ==
9231
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
9232
    {
9233
       WOLFSSL_MSG("Cipher Bits Not Set.");
9234
    }
9235
    /* macStr */
9236
    macStr = GetCipherMacStr(n);
9237
9238
9239
    /* Build up the string by copying onto the end. */
9240
    XSTRNCPY(dp, name, (size_t)len);
9241
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9242
    len -= strLen; dp += strLen;
9243
9244
    XSTRNCPY(dp, " ", (size_t)len);
9245
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9246
    len -= strLen; dp += strLen;
9247
    XSTRNCPY(dp, protocol, (size_t)len);
9248
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9249
    len -= strLen; dp += strLen;
9250
9251
    XSTRNCPY(dp, " Kx=", (size_t)len);
9252
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9253
    len -= strLen; dp += strLen;
9254
    XSTRNCPY(dp, keaStr, (size_t)len);
9255
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9256
    len -= strLen; dp += strLen;
9257
9258
    XSTRNCPY(dp, " Au=", (size_t)len);
9259
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9260
    len -= strLen; dp += strLen;
9261
    XSTRNCPY(dp, authStr, (size_t)len);
9262
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9263
    len -= strLen; dp += strLen;
9264
9265
    XSTRNCPY(dp, " Enc=", (size_t)len);
9266
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9267
    len -= strLen; dp += strLen;
9268
    XSTRNCPY(dp, encStr, (size_t)len);
9269
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9270
    len -= strLen; dp += strLen;
9271
9272
    XSTRNCPY(dp, " Mac=", (size_t)len);
9273
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
9274
    len -= strLen; dp += (size_t)strLen;
9275
    XSTRNCPY(dp, macStr, (size_t)len);
9276
    dp[len-1] = '\0';
9277
9278
    return WOLFSSL_SUCCESS;
9279
}
9280
#endif /* OPENSSL_ALL || WOLFSSL_QT */
9281
9282
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
9283
{
9284
    const char* keaStr;
9285
9286
    switch (kea) {
9287
        case no_kea:
9288
            keaStr = "None";
9289
            break;
9290
#ifndef NO_RSA
9291
        case rsa_kea:
9292
            keaStr = "RSA";
9293
            break;
9294
#endif
9295
#ifndef NO_DH
9296
        case diffie_hellman_kea:
9297
            keaStr = "DHE";
9298
            break;
9299
#endif
9300
        case fortezza_kea:
9301
            keaStr = "FZ";
9302
            break;
9303
#ifndef NO_PSK
9304
        case psk_kea:
9305
            keaStr = "PSK";
9306
            break;
9307
    #ifndef NO_DH
9308
        case dhe_psk_kea:
9309
            keaStr = "DHEPSK";
9310
            break;
9311
    #endif
9312
    #ifdef HAVE_ECC
9313
        case ecdhe_psk_kea:
9314
            keaStr = "ECDHEPSK";
9315
            break;
9316
    #endif
9317
#endif
9318
#ifdef HAVE_ECC
9319
        case ecc_diffie_hellman_kea:
9320
            keaStr = "ECDHE";
9321
            break;
9322
        case ecc_static_diffie_hellman_kea:
9323
            keaStr = "ECDH";
9324
            break;
9325
#endif
9326
        case any_kea:
9327
            keaStr = "any";
9328
            break;
9329
        default:
9330
            keaStr = "unknown";
9331
            break;
9332
    }
9333
9334
    return keaStr;
9335
}
9336
9337
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
9338
{
9339
    const char* authStr;
9340
9341
    switch (sig_algo) {
9342
        case anonymous_sa_algo:
9343
            authStr = "None";
9344
            break;
9345
#ifndef NO_RSA
9346
        case rsa_sa_algo:
9347
            authStr = "RSA";
9348
            break;
9349
    #ifdef WC_RSA_PSS
9350
        case rsa_pss_sa_algo:
9351
            authStr = "RSA-PSS";
9352
            break;
9353
    #endif
9354
#endif
9355
#ifndef NO_DSA
9356
        case dsa_sa_algo:
9357
            authStr = "DSA";
9358
            break;
9359
#endif
9360
#ifdef HAVE_ECC
9361
        case ecc_dsa_sa_algo:
9362
            authStr = "ECDSA";
9363
            break;
9364
#endif
9365
#ifdef WOLFSSL_SM2
9366
        case sm2_sa_algo:
9367
            authStr = "SM2";
9368
            break;
9369
#endif
9370
#ifdef HAVE_ED25519
9371
        case ed25519_sa_algo:
9372
            authStr = "Ed25519";
9373
            break;
9374
#endif
9375
#ifdef HAVE_ED448
9376
        case ed448_sa_algo:
9377
            authStr = "Ed448";
9378
            break;
9379
#endif
9380
        case any_sa_algo:
9381
            authStr = "any";
9382
            break;
9383
        default:
9384
            authStr = "unknown";
9385
            break;
9386
    }
9387
9388
    return authStr;
9389
}
9390
9391
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
9392
{
9393
    const char* encStr;
9394
9395
    (void)key_size;
9396
9397
    switch (cipher) {
9398
        case wolfssl_cipher_null:
9399
            encStr = "None";
9400
            break;
9401
#ifndef NO_RC4
9402
        case wolfssl_rc4:
9403
            encStr = "RC4(128)";
9404
            break;
9405
#endif
9406
#ifndef NO_DES3
9407
        case wolfssl_triple_des:
9408
            encStr = "3DES(168)";
9409
            break;
9410
#endif
9411
#ifndef NO_AES
9412
        case wolfssl_aes:
9413
            if (key_size == AES_128_KEY_SIZE)
9414
                encStr = "AES(128)";
9415
            else if (key_size == AES_256_KEY_SIZE)
9416
                encStr = "AES(256)";
9417
            else
9418
                encStr = "AES(?)";
9419
            break;
9420
    #ifdef HAVE_AESGCM
9421
        case wolfssl_aes_gcm:
9422
            if (key_size == AES_128_KEY_SIZE)
9423
                encStr = "AESGCM(128)";
9424
            else if (key_size == AES_256_KEY_SIZE)
9425
                encStr = "AESGCM(256)";
9426
            else
9427
                encStr = "AESGCM(?)";
9428
            break;
9429
    #endif
9430
    #ifdef HAVE_AESCCM
9431
        case wolfssl_aes_ccm:
9432
            if (key_size == AES_128_KEY_SIZE)
9433
                encStr = "AESCCM(128)";
9434
            else if (key_size == AES_256_KEY_SIZE)
9435
                encStr = "AESCCM(256)";
9436
            else
9437
                encStr = "AESCCM(?)";
9438
            break;
9439
    #endif
9440
#endif
9441
#ifdef HAVE_CHACHA
9442
        case wolfssl_chacha:
9443
            encStr = "CHACHA20/POLY1305(256)";
9444
            break;
9445
#endif
9446
#ifdef HAVE_ARIA
9447
        case wolfssl_aria_gcm:
9448
            if (key_size == ARIA_128_KEY_SIZE)
9449
                encStr = "Aria(128)";
9450
            else if (key_size == ARIA_192_KEY_SIZE)
9451
                encStr = "Aria(192)";
9452
            else if (key_size == ARIA_256_KEY_SIZE)
9453
                encStr = "Aria(256)";
9454
            else
9455
                encStr = "Aria(?)";
9456
            break;
9457
#endif
9458
#ifdef HAVE_CAMELLIA
9459
        case wolfssl_camellia:
9460
            if (key_size == CAMELLIA_128_KEY_SIZE)
9461
                encStr = "Camellia(128)";
9462
            else if (key_size == CAMELLIA_256_KEY_SIZE)
9463
                encStr = "Camellia(256)";
9464
            else
9465
                encStr = "Camellia(?)";
9466
            break;
9467
#endif
9468
        default:
9469
            encStr = "unknown";
9470
            break;
9471
    }
9472
9473
    return encStr;
9474
}
9475
9476
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
9477
{
9478
    const char* macStr;
9479
9480
    switch (mac) {
9481
        case no_mac:
9482
            macStr = "None";
9483
            break;
9484
#ifndef NO_MD5
9485
        case md5_mac:
9486
            macStr = "MD5";
9487
            break;
9488
#endif
9489
#ifndef NO_SHA
9490
        case sha_mac:
9491
            macStr = "SHA1";
9492
            break;
9493
#endif
9494
#ifdef WOLFSSL_SHA224
9495
        case sha224_mac:
9496
            macStr = "SHA224";
9497
            break;
9498
#endif
9499
#ifndef NO_SHA256
9500
        case sha256_mac:
9501
            macStr = "SHA256";
9502
            break;
9503
#endif
9504
#ifdef WOLFSSL_SHA384
9505
        case sha384_mac:
9506
            macStr = "SHA384";
9507
            break;
9508
#endif
9509
#ifdef WOLFSSL_SHA512
9510
        case sha512_mac:
9511
            macStr = "SHA512";
9512
            break;
9513
#endif
9514
        default:
9515
            macStr = "unknown";
9516
            break;
9517
    }
9518
9519
    return macStr;
9520
}
9521
9522
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
9523
                                 int len)
9524
{
9525
    char *ret = in;
9526
    const char *keaStr, *authStr, *encStr, *macStr;
9527
    size_t strLen;
9528
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
9529
9530
    if (cipher == NULL || in == NULL)
9531
        return NULL;
9532
9533
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
9534
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
9535
     * Return the description based on cipher_names[cipher->offset]
9536
     */
9537
    if (cipher->in_stack == TRUE) {
9538
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
9539
        XSTRNCPY(in,cipher->description,(size_t)len);
9540
        return ret;
9541
    }
9542
#endif
9543
9544
    /* Get the cipher description based on the SSL session cipher */
9545
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
9546
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
9547
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
9548
                                      cipher->ssl->specs.key_size);
9549
    if (cipher->ssl->specs.cipher_type == aead)
9550
        macStr = "AEAD";
9551
    else
9552
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
9553
9554
    /* Build up the string by copying onto the end. */
9555
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
9556
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9557
9558
    XSTRNCPY(in, " ", (size_t)len);
9559
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9560
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
9561
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9562
9563
    XSTRNCPY(in, " Kx=", (size_t)len);
9564
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9565
    XSTRNCPY(in, keaStr, (size_t)len);
9566
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9567
9568
    XSTRNCPY(in, " Au=", (size_t)len);
9569
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9570
    XSTRNCPY(in, authStr, (size_t)len);
9571
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9572
9573
    XSTRNCPY(in, " Enc=", (size_t)len);
9574
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9575
    XSTRNCPY(in, encStr, (size_t)len);
9576
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9577
9578
    XSTRNCPY(in, " Mac=", (size_t)len);
9579
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
9580
    XSTRNCPY(in, macStr, (size_t)len);
9581
    in[len-1] = '\0';
9582
9583
    return ret;
9584
}
9585
9586
int wolfSSL_OCSP_parse_url(const char* url, char** host, char** port,
9587
        char** path, int* ssl)
9588
{
9589
    const char* u;
9590
    const char* upath; /* path in u */
9591
    const char* uport; /* port in u */
9592
    const char* hostEnd;
9593
9594
    WOLFSSL_ENTER("OCSP_parse_url");
9595
9596
    if (url == NULL || host == NULL || port == NULL || path == NULL ||
9597
            ssl == NULL) {
9598
        return WOLFSSL_FAILURE;
9599
    }
9600
9601
    u = url;
9602
    *host = NULL;
9603
    *port = NULL;
9604
    *path = NULL;
9605
    *ssl = 0;
9606
9607
    if (*(u++) != 'h') goto err;
9608
    if (*(u++) != 't') goto err;
9609
    if (*(u++) != 't') goto err;
9610
    if (*(u++) != 'p') goto err;
9611
    if (*u == 's') {
9612
        *ssl = 1;
9613
        u++;
9614
        *port = CopyString("443", -1, NULL, DYNAMIC_TYPE_OPENSSL);
9615
    }
9616
    else if (*u == ':') {
9617
        *ssl = 0;
9618
        *port = CopyString("80", -1, NULL, DYNAMIC_TYPE_OPENSSL);
9619
    }
9620
    else
9621
        goto err;
9622
    if (*port == NULL)
9623
        goto err;
9624
    if (*(u++) != ':') goto err;
9625
    if (*(u++) != '/') goto err;
9626
    if (*(u++) != '/') goto err;
9627
9628
    /* Look for path */
9629
    upath = XSTRSTR(u, "/");
9630
    *path = CopyString(upath == NULL ? "/" : upath, -1, NULL,
9631
                       DYNAMIC_TYPE_OPENSSL);
9632
9633
    /* Look for port */
9634
    uport = XSTRSTR(u, ":");
9635
    if (uport != NULL) {
9636
        if (*(++uport) == '\0')
9637
            goto err;
9638
        /* port must be before path */
9639
        if (upath != NULL && uport >= upath)
9640
            goto err;
9641
        XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
9642
        if (upath)
9643
            *port = CopyString(uport, (int)(upath - uport), NULL,
9644
                               DYNAMIC_TYPE_OPENSSL);
9645
        else
9646
            *port = CopyString(uport, -1, NULL, DYNAMIC_TYPE_OPENSSL);
9647
        if (*port == NULL)
9648
            goto err;
9649
        hostEnd = uport - 1;
9650
    }
9651
    else
9652
        hostEnd = upath;
9653
9654
    if (hostEnd)
9655
        *host = CopyString(u, (int)(hostEnd - u), NULL, DYNAMIC_TYPE_OPENSSL);
9656
    else
9657
        *host = CopyString(u, -1, NULL, DYNAMIC_TYPE_OPENSSL);
9658
9659
    if (*host == NULL)
9660
        goto err;
9661
9662
    return WOLFSSL_SUCCESS;
9663
err:
9664
    XFREE(*host, NULL, DYNAMIC_TYPE_OPENSSL);
9665
    *host = NULL;
9666
    XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
9667
    *port = NULL;
9668
    XFREE(*path, NULL, DYNAMIC_TYPE_OPENSSL);
9669
    *path = NULL;
9670
    return WOLFSSL_FAILURE;
9671
}
9672
9673
#ifndef NO_WOLFSSL_STUB
9674
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
9675
{
9676
    WOLFSSL_STUB("COMP_zlib");
9677
    return 0;
9678
}
9679
9680
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
9681
{
9682
    WOLFSSL_STUB("COMP_rle");
9683
    return 0;
9684
}
9685
9686
int wolfSSL_COMP_add_compression_method(int method, void* data)
9687
{
9688
    (void)method;
9689
    (void)data;
9690
    WOLFSSL_STUB("COMP_add_compression_method");
9691
    return 0;
9692
}
9693
9694
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
9695
    (void)ssl;
9696
    return NULL;
9697
}
9698
9699
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
9700
    (void)ssl;
9701
    return NULL;
9702
}
9703
9704
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
9705
{
9706
    static const char ret[] = "not supported";
9707
9708
    (void)comp;
9709
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
9710
    return ret;
9711
}
9712
#endif
9713
9714
/*  wolfSSL_set_dynlock_create_callback
9715
 *  CRYPTO_set_dynlock_create_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_create_callback(WOLFSSL_dynlock_value* (*f)(
9720
                                                          const char*, int))
9721
{
9722
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
9723
    (void)f;
9724
}
9725
/*  wolfSSL_set_dynlock_lock_callback
9726
 *  CRYPTO_set_dynlock_lock_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_lock_callback(
9731
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
9732
{
9733
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
9734
    (void)f;
9735
}
9736
/*  wolfSSL_set_dynlock_destroy_callback
9737
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
9738
 *  This function exists for compatibility purposes because wolfSSL satisfies
9739
 *  thread safety without relying on the callback.
9740
 */
9741
void wolfSSL_set_dynlock_destroy_callback(
9742
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
9743
{
9744
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
9745
    (void)f;
9746
}
9747
9748
/* Sets the DNS hostname to name.
9749
 * Hostname is cleared if name is NULL or empty. */
9750
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
9751
{
9752
    if (ssl == NULL) {
9753
        return WOLFSSL_FAILURE;
9754
    }
9755
9756
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
9757
}
9758
9759
/******************************************************************************
9760
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
9761
*
9762
* RETURNS:
9763
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
9764
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
9765
*   same as openssl.
9766
*/
9767
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
9768
{
9769
    if (ctx == NULL || vpm == NULL)
9770
        return WOLFSSL_SUCCESS;
9771
9772
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
9773
}
9774
9775
/******************************************************************************
9776
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
9777
*
9778
* RETURNS:
9779
* returns pointer to the SSL verification parameters on success,
9780
* otherwise returns NULL
9781
*/
9782
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
9783
{
9784
    if (ctx == NULL) {
9785
        return NULL;
9786
    }
9787
9788
    return ctx->param;
9789
}
9790
9791
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
9792
{
9793
    if (ssl == NULL) {
9794
        return NULL;
9795
    }
9796
    return ssl->param;
9797
}
9798
9799
#endif /* OPENSSL_EXTRA */
9800
9801
9802
#ifdef OPENSSL_EXTRA
9803
/* Sets a function callback that will send information about the state of all
9804
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
9805
 * in.
9806
 *
9807
 * ctx WOLFSSL_CTX structure to set callback function in
9808
 * f   callback function to use
9809
 */
9810
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
9811
       void (*f)(const WOLFSSL* ssl, int type, int val))
9812
{
9813
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
9814
    if (ctx == NULL) {
9815
        WOLFSSL_MSG("Bad function argument");
9816
    }
9817
    else {
9818
        ctx->CBIS = f;
9819
    }
9820
}
9821
9822
void wolfSSL_set_info_callback(WOLFSSL* ssl,
9823
       void (*f)(const WOLFSSL* ssl, int type, int val))
9824
{
9825
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
9826
    if (ssl == NULL) {
9827
        WOLFSSL_MSG("Bad function argument");
9828
    }
9829
    else {
9830
        ssl->CBIS = f;
9831
    }
9832
}
9833
9834
9835
unsigned long wolfSSL_ERR_peek_error(void)
9836
{
9837
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error");
9838
9839
    return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL);
9840
}
9841
9842
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H
9843
#include <wolfssl/debug-untrace-error-codes.h>
9844
#endif
9845
9846
int wolfSSL_ERR_GET_LIB(unsigned long err)
9847
{
9848
    unsigned long value;
9849
9850
    value = (err & 0xFFFFFFL);
9851
    switch (value) {
9852
    case -PARSE_ERROR:
9853
        return WOLFSSL_ERR_LIB_SSL;
9854
    case -ASN_NO_PEM_HEADER:
9855
    case -WOLFSSL_PEM_R_NO_START_LINE_E:
9856
    case -WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E:
9857
    case -WOLFSSL_PEM_R_BAD_PASSWORD_READ_E:
9858
    case -WOLFSSL_PEM_R_BAD_DECRYPT_E:
9859
        return WOLFSSL_ERR_LIB_PEM;
9860
    case -WOLFSSL_EVP_R_BAD_DECRYPT_E:
9861
    case -WOLFSSL_EVP_R_BN_DECODE_ERROR:
9862
    case -WOLFSSL_EVP_R_DECODE_ERROR:
9863
    case -WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR:
9864
        return WOLFSSL_ERR_LIB_EVP;
9865
    case -WOLFSSL_ASN1_R_HEADER_TOO_LONG_E:
9866
        return WOLFSSL_ERR_LIB_ASN1;
9867
    default:
9868
        return 0;
9869
    }
9870
}
9871
9872
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES
9873
#include <wolfssl/debug-trace-error-codes.h>
9874
#endif
9875
9876
/* This function is to find global error values that are the same through out
9877
 * all library version. With wolfSSL having only one set of error codes the
9878
 * return value is pretty straight forward. The only thing needed is all wolfSSL
9879
 * error values are typically negative.
9880
 *
9881
 * Returns the error reason
9882
 */
9883
int wolfSSL_ERR_GET_REASON(unsigned long err)
9884
{
9885
    int ret = (int)err;
9886
9887
    WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON");
9888
9889
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
9890
    /* Nginx looks for this error to know to stop parsing certificates.
9891
     * Same for HAProxy. */
9892
    if ((err == (unsigned long)((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE)) ||
9893
        ((err & 0xFFFFFFL) == (unsigned long)(-WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))) ||
9894
        ((err & 0xFFFL) == (unsigned long)PEM_R_NO_START_LINE))
9895
        return PEM_R_NO_START_LINE;
9896
    if (err == (unsigned long)((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST))
9897
        return SSL_R_HTTP_REQUEST;
9898
#endif
9899
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
9900
    if (err == (unsigned long)((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG))
9901
        return ASN1_R_HEADER_TOO_LONG;
9902
#endif
9903
9904
    /* check if error value is in range of wolfCrypt or wolfSSL errors */
9905
    ret = 0 - ret; /* setting as negative value */
9906
9907
    if ((ret <= WC_SPAN1_FIRST_E && ret >= WC_SPAN1_LAST_E) ||
9908
        (ret <= WC_SPAN2_FIRST_E && ret >= WC_SPAN2_LAST_E) ||
9909
        (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E))
9910
    {
9911
        return ret;
9912
    }
9913
    else {
9914
        WOLFSSL_MSG("Not in range of typical error values");
9915
        ret = (int)err;
9916
    }
9917
9918
    return ret;
9919
}
9920
9921
#ifndef NO_TLS
9922
/* returns a string that describes the alert
9923
 *
9924
 * alertID the alert value to look up
9925
 */
9926
const char* wolfSSL_alert_type_string_long(int alertID)
9927
{
9928
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
9929
9930
    return AlertTypeToString(alertID);
9931
}
9932
9933
const char* wolfSSL_alert_type_string(int alertID)
9934
{
9935
    WOLFSSL_ENTER("wolfSSL_alert_type_string");
9936
9937
    switch (alertID) {
9938
        case alert_warning:
9939
            return "W";
9940
        case alert_fatal:
9941
            return "F";
9942
        default:
9943
            return "U";
9944
    }
9945
}
9946
9947
const char* wolfSSL_alert_desc_string_long(int alertID)
9948
{
9949
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
9950
9951
    return AlertTypeToString(alertID);
9952
}
9953
9954
const char* wolfSSL_alert_desc_string(int alertID)
9955
{
9956
    WOLFSSL_ENTER("wolfSSL_alert_desc_string");
9957
9958
    switch (alertID) {
9959
        case close_notify:
9960
            return "CN";
9961
        case unexpected_message:
9962
            return "UM";
9963
        case bad_record_mac:
9964
            return "BM";
9965
        case record_overflow:
9966
            return "RO";
9967
        case decompression_failure:
9968
            return "DF";
9969
        case handshake_failure:
9970
            return "HF";
9971
        case no_certificate:
9972
            return "NC";
9973
        case bad_certificate:
9974
            return "BC";
9975
        case unsupported_certificate:
9976
            return "UC";
9977
        case certificate_revoked:
9978
            return "CR";
9979
        case certificate_expired:
9980
            return "CE";
9981
        case certificate_unknown:
9982
            return "CU";
9983
        case illegal_parameter:
9984
            return "IP";
9985
        case unknown_ca:
9986
            return "CA";
9987
        case access_denied:
9988
            return "AD";
9989
        case decode_error:
9990
            return "DE";
9991
        case decrypt_error:
9992
            return "DC";
9993
        case wolfssl_alert_protocol_version:
9994
            return "PV";
9995
        case insufficient_security:
9996
            return "IS";
9997
        case internal_error:
9998
            return "IE";
9999
        case inappropriate_fallback:
10000
            return "IF";
10001
        case user_canceled:
10002
            return "US";
10003
        case no_renegotiation:
10004
            return "NR";
10005
        case missing_extension:
10006
            return "ME";
10007
        case unsupported_extension:
10008
            return "UE";
10009
        case unrecognized_name:
10010
            return "UN";
10011
        case bad_certificate_status_response:
10012
            return "BR";
10013
        case unknown_psk_identity:
10014
            return "UP";
10015
        case certificate_required:
10016
            return "CQ";
10017
        case no_application_protocol:
10018
            return "AP";
10019
        default:
10020
            return "UK";
10021
    }
10022
}
10023
#endif /* !NO_TLS */
10024
10025
#define STATE_STRINGS_PROTO(s) \
10026
    {                          \
10027
        {"SSLv3 " s,           \
10028
         "SSLv3 " s,           \
10029
         "SSLv3 " s},          \
10030
        {"TLSv1 " s,           \
10031
         "TLSv1 " s,           \
10032
         "TLSv1 " s},          \
10033
        {"TLSv1_1 " s,         \
10034
         "TLSv1_1 " s,         \
10035
         "TLSv1_1 " s},        \
10036
        {"TLSv1_2 " s,         \
10037
         "TLSv1_2 " s,         \
10038
         "TLSv1_2 " s},        \
10039
        {"TLSv1_3 " s,         \
10040
         "TLSv1_3 " s,         \
10041
         "TLSv1_3 " s},        \
10042
        {"DTLSv1 " s,          \
10043
         "DTLSv1 " s,          \
10044
         "DTLSv1 " s},         \
10045
        {"DTLSv1_2 " s,        \
10046
         "DTLSv1_2 " s,        \
10047
         "DTLSv1_2 " s},       \
10048
        {"DTLSv1_3 " s,        \
10049
         "DTLSv1_3 " s,        \
10050
         "DTLSv1_3 " s},       \
10051
    }
10052
10053
#define STATE_STRINGS_PROTO_RW(s) \
10054
    {                             \
10055
        {"SSLv3 read " s,         \
10056
         "SSLv3 write " s,        \
10057
         "SSLv3 " s},             \
10058
        {"TLSv1 read " s,         \
10059
         "TLSv1 write " s,        \
10060
         "TLSv1 " s},             \
10061
        {"TLSv1_1 read " s,       \
10062
         "TLSv1_1 write " s,      \
10063
         "TLSv1_1 " s},           \
10064
        {"TLSv1_2 read " s,       \
10065
         "TLSv1_2 write " s,      \
10066
         "TLSv1_2 " s},           \
10067
        {"TLSv1_3 read " s,       \
10068
         "TLSv1_3 write " s,      \
10069
         "TLSv1_3 " s},           \
10070
        {"DTLSv1 read " s,        \
10071
         "DTLSv1 write " s,       \
10072
         "DTLSv1 " s},            \
10073
        {"DTLSv1_2 read " s,      \
10074
         "DTLSv1_2 write " s,     \
10075
         "DTLSv1_2 " s},          \
10076
        {"DTLSv1_3 read " s,      \
10077
         "DTLSv1_3 write " s,     \
10078
         "DTLSv1_3 " s},          \
10079
    }
10080
10081
/* Gets the current state of the WOLFSSL structure
10082
 *
10083
 * ssl WOLFSSL structure to get state of
10084
 *
10085
 * Returns a human readable string of the WOLFSSL structure state
10086
 */
10087
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
10088
{
10089
10090
    static const char* OUTPUT_STR[24][8][3] = {
10091
        STATE_STRINGS_PROTO("Initialization"),
10092
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
10093
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
10094
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
10095
        STATE_STRINGS_PROTO_RW("Server Hello"),
10096
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
10097
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
10098
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
10099
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
10100
        STATE_STRINGS_PROTO_RW("Server Cert"),
10101
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
10102
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
10103
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
10104
        STATE_STRINGS_PROTO_RW("Server Finished"),
10105
        STATE_STRINGS_PROTO_RW("server Key Update"),
10106
        STATE_STRINGS_PROTO_RW("Client Hello"),
10107
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
10108
        STATE_STRINGS_PROTO_RW("Client Cert"),
10109
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
10110
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
10111
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
10112
        STATE_STRINGS_PROTO_RW("Client Finished"),
10113
        STATE_STRINGS_PROTO_RW("Client Key Update"),
10114
        STATE_STRINGS_PROTO("Handshake Done"),
10115
    };
10116
    enum ProtocolVer {
10117
        SSL_V3 = 0,
10118
        TLS_V1,
10119
        TLS_V1_1,
10120
        TLS_V1_2,
10121
        TLS_V1_3,
10122
        DTLS_V1,
10123
        DTLS_V1_2,
10124
        DTLS_V1_3,
10125
        UNKNOWN = 100
10126
    };
10127
10128
    enum IOMode {
10129
        SS_READ = 0,
10130
        SS_WRITE,
10131
        SS_NEITHER
10132
    };
10133
10134
    enum SslState {
10135
        ss_null_state = 0,
10136
        ss_server_hellorequest,
10137
        ss_server_helloverify,
10138
        ss_server_helloretryrequest,
10139
        ss_server_hello,
10140
        ss_server_certificatestatus,
10141
        ss_server_encryptedextensions,
10142
        ss_server_sessionticket,
10143
        ss_server_certrequest,
10144
        ss_server_cert,
10145
        ss_server_keyexchange,
10146
        ss_server_hellodone,
10147
        ss_server_changecipherspec,
10148
        ss_server_finished,
10149
        ss_server_keyupdate,
10150
        ss_client_hello,
10151
        ss_client_keyexchange,
10152
        ss_client_cert,
10153
        ss_client_changecipherspec,
10154
        ss_client_certverify,
10155
        ss_client_endofearlydata,
10156
        ss_client_finished,
10157
        ss_client_keyupdate,
10158
        ss_handshake_done
10159
    };
10160
10161
    int protocol = 0;
10162
    int cbmode = 0;
10163
    int state = 0;
10164
10165
    WOLFSSL_ENTER("wolfSSL_state_string_long");
10166
    if (ssl == NULL) {
10167
        WOLFSSL_MSG("Null argument passed in");
10168
        return NULL;
10169
    }
10170
10171
    /* Get state of callback */
10172
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
10173
        cbmode =  SS_WRITE;
10174
    }
10175
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
10176
        cbmode =  SS_READ;
10177
    }
10178
    else {
10179
        cbmode =  SS_NEITHER;
10180
    }
10181
10182
    /* Get protocol version */
10183
    switch (ssl->version.major) {
10184
        case SSLv3_MAJOR:
10185
            switch (ssl->version.minor) {
10186
                case SSLv3_MINOR:
10187
                    protocol = SSL_V3;
10188
                    break;
10189
                case TLSv1_MINOR:
10190
                    protocol = TLS_V1;
10191
                    break;
10192
                case TLSv1_1_MINOR:
10193
                    protocol = TLS_V1_1;
10194
                    break;
10195
                case TLSv1_2_MINOR:
10196
                    protocol = TLS_V1_2;
10197
                    break;
10198
                case TLSv1_3_MINOR:
10199
                    protocol = TLS_V1_3;
10200
                    break;
10201
                default:
10202
                    protocol = UNKNOWN;
10203
            }
10204
            break;
10205
        case DTLS_MAJOR:
10206
            switch (ssl->version.minor) {
10207
                case DTLS_MINOR:
10208
                    protocol = DTLS_V1;
10209
                    break;
10210
                case DTLSv1_2_MINOR:
10211
                    protocol = DTLS_V1_2;
10212
                    break;
10213
                case DTLSv1_3_MINOR:
10214
                    protocol = DTLS_V1_3;
10215
                    break;
10216
                default:
10217
                    protocol = UNKNOWN;
10218
            }
10219
            break;
10220
    default:
10221
        protocol = UNKNOWN;
10222
    }
10223
10224
    /* accept process */
10225
    if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
10226
        state = ssl->cbtype;
10227
        switch (state) {
10228
            case hello_request:
10229
                state = ss_server_hellorequest;
10230
                break;
10231
            case client_hello:
10232
                state = ss_client_hello;
10233
                break;
10234
            case server_hello:
10235
                state = ss_server_hello;
10236
                break;
10237
            case hello_verify_request:
10238
                state = ss_server_helloverify;
10239
                break;
10240
            case session_ticket:
10241
                state = ss_server_sessionticket;
10242
                break;
10243
            case end_of_early_data:
10244
                state = ss_client_endofearlydata;
10245
                break;
10246
            case hello_retry_request:
10247
                state = ss_server_helloretryrequest;
10248
                break;
10249
            case encrypted_extensions:
10250
                state = ss_server_encryptedextensions;
10251
                break;
10252
            case certificate:
10253
                if (ssl->options.side == WOLFSSL_SERVER_END)
10254
                    state = ss_client_cert;
10255
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10256
                    state = ss_server_cert;
10257
                else {
10258
                    WOLFSSL_MSG("Unknown State");
10259
                    state = ss_null_state;
10260
                }
10261
                break;
10262
            case server_key_exchange:
10263
                state = ss_server_keyexchange;
10264
                break;
10265
            case certificate_request:
10266
                state = ss_server_certrequest;
10267
                break;
10268
            case server_hello_done:
10269
                state = ss_server_hellodone;
10270
                break;
10271
            case certificate_verify:
10272
                state = ss_client_certverify;
10273
                break;
10274
            case client_key_exchange:
10275
                state = ss_client_keyexchange;
10276
                break;
10277
            case finished:
10278
                if (ssl->options.side == WOLFSSL_SERVER_END)
10279
                    state = ss_client_finished;
10280
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10281
                    state = ss_server_finished;
10282
                else {
10283
                    WOLFSSL_MSG("Unknown State");
10284
                    state = ss_null_state;
10285
                }
10286
                break;
10287
            case certificate_status:
10288
                state = ss_server_certificatestatus;
10289
                break;
10290
            case key_update:
10291
                if (ssl->options.side == WOLFSSL_SERVER_END)
10292
                    state = ss_client_keyupdate;
10293
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10294
                    state = ss_server_keyupdate;
10295
                else {
10296
                    WOLFSSL_MSG("Unknown State");
10297
                    state = ss_null_state;
10298
                }
10299
                break;
10300
            case change_cipher_hs:
10301
                if (ssl->options.side == WOLFSSL_SERVER_END)
10302
                    state = ss_client_changecipherspec;
10303
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
10304
                    state = ss_server_changecipherspec;
10305
                else {
10306
                    WOLFSSL_MSG("Unknown State");
10307
                    state = ss_null_state;
10308
                }
10309
                break;
10310
            default:
10311
                WOLFSSL_MSG("Unknown State");
10312
                state = ss_null_state;
10313
        }
10314
    }
10315
    else {
10316
        /* Send process */
10317
        if (ssl->options.side == WOLFSSL_SERVER_END)
10318
            state = ssl->options.serverState;
10319
        else
10320
            state = ssl->options.clientState;
10321
10322
        switch (state) {
10323
            case SERVER_HELLOVERIFYREQUEST_COMPLETE:
10324
                state = ss_server_helloverify;
10325
                break;
10326
            case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
10327
                state = ss_server_helloretryrequest;
10328
                break;
10329
            case SERVER_HELLO_COMPLETE:
10330
                state = ss_server_hello;
10331
                break;
10332
            case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
10333
                state = ss_server_encryptedextensions;
10334
                break;
10335
            case SERVER_CERT_COMPLETE:
10336
                state = ss_server_cert;
10337
                break;
10338
            case SERVER_KEYEXCHANGE_COMPLETE:
10339
                state = ss_server_keyexchange;
10340
                break;
10341
            case SERVER_HELLODONE_COMPLETE:
10342
                state = ss_server_hellodone;
10343
                break;
10344
            case SERVER_CHANGECIPHERSPEC_COMPLETE:
10345
                state = ss_server_changecipherspec;
10346
                break;
10347
            case SERVER_FINISHED_COMPLETE:
10348
                state = ss_server_finished;
10349
                break;
10350
            case CLIENT_HELLO_RETRY:
10351
            case CLIENT_HELLO_COMPLETE:
10352
                state = ss_client_hello;
10353
                break;
10354
            case CLIENT_KEYEXCHANGE_COMPLETE:
10355
                state = ss_client_keyexchange;
10356
                break;
10357
            case CLIENT_CHANGECIPHERSPEC_COMPLETE:
10358
                state = ss_client_changecipherspec;
10359
                break;
10360
            case CLIENT_FINISHED_COMPLETE:
10361
                state = ss_client_finished;
10362
                break;
10363
            case HANDSHAKE_DONE:
10364
                state = ss_handshake_done;
10365
                break;
10366
            default:
10367
                WOLFSSL_MSG("Unknown State");
10368
                state = ss_null_state;
10369
        }
10370
    }
10371
10372
    if (protocol == UNKNOWN) {
10373
        WOLFSSL_MSG("Unknown protocol");
10374
        return "";
10375
    }
10376
    else {
10377
        return OUTPUT_STR[state][protocol][cbmode];
10378
    }
10379
}
10380
10381
#endif /* OPENSSL_EXTRA */
10382
10383
static long wolf_set_options(long old_op, long op)
10384
0
{
10385
    /* if SSL_OP_ALL then turn all bug workarounds on */
10386
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
10387
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
10388
0
    }
10389
10390
    /* by default cookie exchange is on with DTLS */
10391
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
10392
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
10393
0
    }
10394
10395
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
10396
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
10397
0
    }
10398
10399
#ifdef SSL_OP_NO_TLSv1_3
10400
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
10401
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
10402
    }
10403
#endif
10404
10405
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
10406
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
10407
0
    }
10408
10409
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
10410
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
10411
0
    }
10412
10413
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
10414
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
10415
0
    }
10416
10417
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
10418
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
10419
0
    }
10420
10421
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
10422
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
10423
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
10424
0
    }
10425
10426
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
10427
    #ifdef HAVE_LIBZ
10428
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
10429
    #else
10430
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
10431
0
    #endif
10432
0
    }
10433
10434
0
    return old_op | op;
10435
0
}
10436
10437
static int FindHashSig(const Suites* suites, byte first, byte second)
10438
0
{
10439
0
    word16 i;
10440
10441
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
10442
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
10443
0
        return SUITES_ERROR;
10444
0
    }
10445
10446
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
10447
0
        if (suites->hashSigAlgo[i]   == first &&
10448
0
            suites->hashSigAlgo[i+1] == second )
10449
0
            return i;
10450
0
    }
10451
10452
0
    return MATCH_SUITE_ERROR;
10453
0
}
10454
10455
long wolfSSL_set_options(WOLFSSL* ssl, long op)
10456
0
{
10457
0
    word16 haveRSA = 1;
10458
0
    word16 havePSK = 0;
10459
0
    int    keySz   = 0;
10460
10461
0
    WOLFSSL_ENTER("wolfSSL_set_options");
10462
10463
0
    if (ssl == NULL) {
10464
0
        return 0;
10465
0
    }
10466
10467
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
10468
10469
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
10470
0
        WOLFSSL_MSG("Disabling TLS 1.3");
10471
0
        if (ssl->version.minor == TLSv1_3_MINOR)
10472
0
            ssl->version.minor = TLSv1_2_MINOR;
10473
0
    }
10474
10475
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
10476
0
        WOLFSSL_MSG("Disabling TLS 1.2");
10477
0
        if (ssl->version.minor == TLSv1_2_MINOR)
10478
0
            ssl->version.minor = TLSv1_1_MINOR;
10479
0
    }
10480
10481
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
10482
0
        WOLFSSL_MSG("Disabling TLS 1.1");
10483
0
        if (ssl->version.minor == TLSv1_1_MINOR)
10484
0
            ssl->version.minor = TLSv1_MINOR;
10485
0
    }
10486
10487
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
10488
0
        WOLFSSL_MSG("Disabling TLS 1.0");
10489
0
        if (ssl->version.minor == TLSv1_MINOR)
10490
0
            ssl->version.minor = SSLv3_MINOR;
10491
0
    }
10492
10493
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
10494
0
        == WOLFSSL_OP_NO_COMPRESSION) {
10495
    #ifdef HAVE_LIBZ
10496
        ssl->options.usingCompression = 0;
10497
    #endif
10498
0
    }
10499
10500
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
10501
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
10502
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
10503
      ssl->options.noTicketTls12 = 1;
10504
    }
10505
#endif
10506
10507
10508
    /* in the case of a version change the cipher suites should be reset */
10509
#ifndef NO_PSK
10510
    havePSK = ssl->options.havePSK;
10511
#endif
10512
#ifdef NO_RSA
10513
    haveRSA = 0;
10514
#endif
10515
0
#ifndef NO_CERTS
10516
0
    keySz = ssl->buffers.keySz;
10517
0
#endif
10518
10519
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
10520
0
        if (AllocateSuites(ssl) != 0)
10521
0
            return 0;
10522
0
        if (!ssl->suites->setSuites) {
10523
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
10524
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
10525
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
10526
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
10527
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
10528
0
                       ssl->options.useAnon,
10529
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
10530
0
            else
10531
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
10532
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
10533
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
10534
0
                       ssl->options.useAnon,
10535
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
10536
0
        }
10537
0
        else {
10538
            /* Only preserve overlapping suites */
10539
0
            Suites tmpSuites;
10540
0
            word16 in, out;
10541
0
            word16 haveECDSAsig, haveStaticECC;
10542
#ifdef NO_RSA
10543
            haveECDSAsig = 1;
10544
            haveStaticECC = 1;
10545
#else
10546
0
            haveECDSAsig = 0;
10547
0
            haveStaticECC = ssl->options.haveStaticECC;
10548
0
#endif
10549
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
10550
            /* Get all possible ciphers and sigalgs for the version. Following
10551
             * options limit the allowed ciphers so let's try to get as many as
10552
             * possible.
10553
             * - haveStaticECC turns off haveRSA
10554
             * - haveECDSAsig turns off haveRSAsig */
10555
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
10556
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
10557
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
10558
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
10559
0
                        ssl->suites->suites[in+1]) >= 0) {
10560
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
10561
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
10562
0
                    out += SUITE_LEN;
10563
0
                }
10564
0
            }
10565
0
            ssl->suites->suiteSz = out;
10566
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
10567
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
10568
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
10569
0
                    ssl->suites->hashSigAlgo[out] =
10570
0
                            ssl->suites->hashSigAlgo[in];
10571
0
                    ssl->suites->hashSigAlgo[out+1] =
10572
0
                            ssl->suites->hashSigAlgo[in+1];
10573
0
                    out += 2;
10574
0
                }
10575
0
            }
10576
0
            ssl->suites->hashSigAlgoSz = out;
10577
0
        }
10578
0
    }
10579
10580
0
    return (long)ssl->options.mask;
10581
0
}
10582
10583
10584
long wolfSSL_get_options(const WOLFSSL* ssl)
10585
62.3k
{
10586
62.3k
    WOLFSSL_ENTER("wolfSSL_get_options");
10587
62.3k
    if(ssl == NULL)
10588
0
        return WOLFSSL_FAILURE;
10589
62.3k
    return (long)ssl->options.mask;
10590
62.3k
}
10591
10592
#if defined(HAVE_SECURE_RENEGOTIATION) \
10593
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
10594
/* clears the counter for number of renegotiations done
10595
 * returns the current count before it is cleared */
10596
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
10597
0
{
10598
0
    long total;
10599
10600
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
10601
0
    if (s == NULL)
10602
0
        return 0;
10603
10604
0
    total = s->secure_rene_count;
10605
0
    s->secure_rene_count = 0;
10606
0
    return total;
10607
0
}
10608
10609
10610
/* return the number of renegotiations since wolfSSL_new */
10611
long wolfSSL_total_renegotiations(WOLFSSL *s)
10612
0
{
10613
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
10614
0
    return wolfSSL_num_renegotiations(s);
10615
0
}
10616
10617
10618
/* return the number of renegotiations since wolfSSL_new */
10619
long wolfSSL_num_renegotiations(WOLFSSL* s)
10620
0
{
10621
0
    if (s == NULL) {
10622
0
        return 0;
10623
0
    }
10624
10625
0
    return s->secure_rene_count;
10626
0
}
10627
10628
10629
/* Is there a renegotiation currently in progress? */
10630
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
10631
0
{
10632
0
    return s && s->options.handShakeDone &&
10633
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
10634
0
}
10635
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
10636
10637
#ifdef OPENSSL_EXTRA
10638
10639
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
10640
{
10641
    WOLFSSL_ENTER("wolfSSL_clear_options");
10642
    if(ssl == NULL)
10643
        return WOLFSSL_FAILURE;
10644
    ssl->options.mask &= (unsigned long)~opt;
10645
    return (long)ssl->options.mask;
10646
}
10647
10648
10649
#ifndef NO_WOLFSSL_STUB
10650
/*** TBD ***/
10651
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
10652
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
10653
{
10654
    (void)ctx;
10655
    (void)dh;
10656
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
10657
}
10658
#endif
10659
10660
#ifndef NO_WOLFSSL_STUB
10661
/*** TBD ***/
10662
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
10663
{
10664
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
10665
    return NULL;
10666
}
10667
#endif
10668
10669
10670
#if !defined(NETOS)
10671
void wolfSSL_ERR_load_SSL_strings(void)
10672
{
10673
10674
}
10675
#endif
10676
10677
10678
#endif /* OPENSSL_EXTRA */
10679
10680
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
10681
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
10682
{
10683
    byte len = 0;
10684
    byte const * src;
10685
10686
    WOLFSSL_ENTER("wolfSSL_get_finished");
10687
10688
    if (!ssl || !buf) {
10689
        WOLFSSL_MSG("Bad parameter");
10690
        return WOLFSSL_FAILURE;
10691
    }
10692
10693
    if (ssl->options.side == WOLFSSL_SERVER_END) {
10694
        src = ssl->serverFinished;
10695
        len = ssl->serverFinished_len;
10696
    }
10697
    else {
10698
        src = ssl->clientFinished;
10699
        len = ssl->clientFinished_len;
10700
    }
10701
10702
    if (count < len) {
10703
        WOLFSSL_MSG("Buffer too small");
10704
        return WOLFSSL_FAILURE;
10705
    }
10706
10707
    XMEMCPY(buf, src, len);
10708
10709
    return len;
10710
}
10711
10712
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
10713
{
10714
    byte len = 0;
10715
    byte const * src;
10716
10717
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
10718
10719
    if (!ssl || !buf) {
10720
        WOLFSSL_MSG("Bad parameter");
10721
        return WOLFSSL_FAILURE;
10722
    }
10723
10724
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
10725
        src = ssl->serverFinished;
10726
        len = ssl->serverFinished_len;
10727
    }
10728
    else {
10729
        src = ssl->clientFinished;
10730
        len = ssl->clientFinished_len;
10731
    }
10732
10733
    if (count < len) {
10734
        WOLFSSL_MSG("Buffer too small");
10735
        return WOLFSSL_FAILURE;
10736
    }
10737
10738
    XMEMCPY(buf, src, len);
10739
10740
    return len;
10741
}
10742
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
10743
10744
10745
#ifdef OPENSSL_EXTRA
10746
10747
#ifndef NO_WOLFSSL_STUB
10748
/* shows the number of accepts attempted by CTX in it's lifetime */
10749
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
10750
{
10751
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
10752
    (void)ctx;
10753
    return 0;
10754
}
10755
#endif
10756
10757
#ifndef NO_WOLFSSL_STUB
10758
/* shows the number of connects attempted CTX in it's lifetime */
10759
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
10760
{
10761
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
10762
    (void)ctx;
10763
    return 0;
10764
}
10765
#endif
10766
10767
10768
#ifndef NO_WOLFSSL_STUB
10769
/* shows the number of accepts completed by CTX in it's lifetime */
10770
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
10771
{
10772
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
10773
    (void)ctx;
10774
    return 0;
10775
}
10776
#endif
10777
10778
10779
#ifndef NO_WOLFSSL_STUB
10780
/* shows the number of connects completed by CTX in it's lifetime */
10781
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
10782
{
10783
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
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_accept_renegotiate(WOLFSSL_CTX* ctx)
10793
{
10794
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
10795
    (void)ctx;
10796
    return 0;
10797
}
10798
#endif
10799
10800
10801
#ifndef NO_WOLFSSL_STUB
10802
/* shows the number of renegotiation accepts attempted by CTX */
10803
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
10804
{
10805
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
10806
    (void)ctx;
10807
    return 0;
10808
}
10809
#endif
10810
10811
10812
#ifndef NO_WOLFSSL_STUB
10813
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
10814
{
10815
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
10816
    (void)ctx;
10817
    return 0;
10818
}
10819
#endif
10820
10821
10822
#ifndef NO_WOLFSSL_STUB
10823
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
10824
{
10825
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
10826
    (void)ctx;
10827
    return 0;
10828
}
10829
#endif
10830
10831
10832
#ifndef NO_WOLFSSL_STUB
10833
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
10834
{
10835
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
10836
    (void)ctx;
10837
    return 0;
10838
}
10839
#endif
10840
10841
10842
#ifndef NO_WOLFSSL_STUB
10843
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
10844
{
10845
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
10846
    (void)ctx;
10847
    return 0;
10848
}
10849
#endif
10850
10851
10852
#ifndef NO_WOLFSSL_STUB
10853
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
10854
{
10855
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
10856
    (void)ctx;
10857
    return 0;
10858
}
10859
#endif
10860
10861
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
10862
{
10863
    if (ssl == NULL) {
10864
        return WOLFSSL_FAILURE;
10865
    }
10866
10867
    return ssl->readAhead;
10868
}
10869
10870
10871
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
10872
{
10873
    if (ssl == NULL) {
10874
        return WOLFSSL_FAILURE;
10875
    }
10876
10877
    ssl->readAhead = (byte)v;
10878
10879
    return WOLFSSL_SUCCESS;
10880
}
10881
10882
10883
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
10884
{
10885
    if (ctx == NULL) {
10886
        return WOLFSSL_FAILURE;
10887
    }
10888
10889
    return ctx->readAhead;
10890
}
10891
10892
10893
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
10894
{
10895
    if (ctx == NULL) {
10896
        return WOLFSSL_FAILURE;
10897
    }
10898
10899
    ctx->readAhead = (byte)v;
10900
10901
    return WOLFSSL_SUCCESS;
10902
}
10903
10904
10905
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
10906
        void* arg)
10907
{
10908
    if (ctx == NULL) {
10909
        return WOLFSSL_FAILURE;
10910
    }
10911
10912
    ctx->userPRFArg = arg;
10913
    return WOLFSSL_SUCCESS;
10914
}
10915
10916
#endif /* OPENSSL_EXTRA */
10917
10918
10919
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
10920
const WOLFSSL_ObjectInfo wolfssl_object_info[] = {
10921
#ifndef NO_CERTS
10922
    /* oidCertExtType */
10923
    { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType,
10924
      "basicConstraints", "X509v3 Basic Constraints"},
10925
    { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName",
10926
      "X509v3 Subject Alternative Name"},
10927
    { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType,
10928
      "crlDistributionPoints", "X509v3 CRL Distribution Points"},
10929
    { WC_NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess",
10930
      "Authority Information Access"},
10931
    { WC_NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType,
10932
      "authorityKeyIdentifier", "X509v3 Authority Key Identifier"},
10933
    { WC_NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType,
10934
      "subjectKeyIdentifier", "X509v3 Subject Key Identifier"},
10935
    { WC_NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage",
10936
      "X509v3 Key Usage"},
10937
    { WC_NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType,
10938
      "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"},
10939
    { WC_NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType,
10940
      "extendedKeyUsage", "X509v3 Extended Key Usage"},
10941
    { WC_NID_name_constraints, NAME_CONS_OID, oidCertExtType,
10942
      "nameConstraints", "X509v3 Name Constraints"},
10943
    { WC_NID_certificate_policies, CERT_POLICY_OID, oidCertExtType,
10944
      "certificatePolicies", "X509v3 Certificate Policies"},
10945
10946
    /* oidCertAuthInfoType */
10947
    { WC_NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP",
10948
      "OCSP"},
10949
    { WC_NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType,
10950
      "caIssuers", "CA Issuers"},
10951
10952
    /* oidCertPolicyType */
10953
    { WC_NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy",
10954
      "X509v3 Any Policy"},
10955
10956
    /* oidCertAltNameType */
10957
    { WC_NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""},
10958
10959
    /* oidCertKeyUseType */
10960
    { WC_NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType,
10961
      "anyExtendedKeyUsage", "Any Extended Key Usage"},
10962
    { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType,
10963
      "serverAuth", "TLS Web Server Authentication"},
10964
    { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType,
10965
      "clientAuth", "TLS Web Client Authentication"},
10966
    { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType,
10967
      "OCSPSigning", "OCSP Signing"},
10968
10969
    /* oidCertNameType */
10970
    { WC_NID_commonName, WC_NAME_COMMON_NAME_OID, oidCertNameType,
10971
      "CN", "commonName"},
10972
#if !defined(WOLFSSL_CERT_REQ)
10973
    { WC_NID_surname, WC_NAME_SURNAME_OID, oidCertNameType, "SN", "surname"},
10974
#endif
10975
    { WC_NID_serialNumber, WC_NAME_SERIAL_NUMBER_OID, oidCertNameType,
10976
      "serialNumber", "serialNumber"},
10977
    { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"},
10978
    { WC_NID_countryName, WC_NAME_COUNTRY_NAME_OID, oidCertNameType,
10979
      "C", "countryName"},
10980
    { WC_NID_localityName, WC_NAME_LOCALITY_NAME_OID, oidCertNameType,
10981
      "L", "localityName"},
10982
    { WC_NID_stateOrProvinceName, WC_NAME_STATE_NAME_OID, oidCertNameType,
10983
      "ST", "stateOrProvinceName"},
10984
    { WC_NID_streetAddress, WC_NAME_STREET_ADDRESS_OID, oidCertNameType,
10985
      "street", "streetAddress"},
10986
    { WC_NID_organizationName, WC_NAME_ORGANIZATION_NAME_OID, oidCertNameType,
10987
      "O", "organizationName"},
10988
    { WC_NID_organizationalUnitName, WC_NAME_ORGANIZATION_UNIT_NAME_OID,
10989
      oidCertNameType, "OU", "organizationalUnitName"},
10990
    { WC_NID_title, WC_NAME_TITLE_OID, oidCertNameType, "title", "title"},
10991
    { WC_NID_description, WC_NAME_DESCRIPTION_OID, oidCertNameType,
10992
      "description", "description"},
10993
    { WC_NID_emailAddress, WC_NAME_EMAIL_ADDRESS_OID, oidCertNameType,
10994
      "emailAddress", "emailAddress"},
10995
    { WC_NID_domainComponent, WC_NAME_DOMAIN_COMPONENT_OID, oidCertNameType,
10996
      "DC", "domainComponent"},
10997
    { WC_NID_rfc822Mailbox, WC_NAME_RFC822_MAILBOX_OID, oidCertNameType,
10998
      "rfc822Mailbox", "rfc822Mailbox"},
10999
    { WC_NID_favouriteDrink, WC_NAME_FAVOURITE_DRINK_OID, oidCertNameType,
11000
      "favouriteDrink", "favouriteDrink"},
11001
    { WC_NID_businessCategory, WC_NAME_BUSINESS_CATEGORY_OID, oidCertNameType,
11002
      "businessCategory", "businessCategory"},
11003
    { WC_NID_jurisdictionCountryName, WC_NAME_JURIS_COUNTRY_OID,
11004
      oidCertNameType, "jurisdictionC", "jurisdictionCountryName"},
11005
    { WC_NID_jurisdictionStateOrProvinceName, WC_NAME_JURIS_STATE_PROV_OID,
11006
      oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"},
11007
    { WC_NID_postalCode, WC_NAME_POSTAL_CODE_OID, oidCertNameType, "postalCode",
11008
      "postalCode"},
11009
    { WC_NID_userId, WC_NAME_USER_ID_OID, oidCertNameType, "UID", "userId"},
11010
    { WC_NID_netscape_cert_type, NETSCAPE_CT_OID, oidCertNameType,
11011
      "nsCertType", "Netscape Cert Type"},
11012
11013
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL)
11014
    { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID,
11015
            oidCsrAttrType, "challengePassword", "challengePassword"},
11016
    { WC_NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID,
11017
        oidCsrAttrType, "contentType", "contentType" },
11018
    { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID,
11019
        oidCsrAttrType, "unstructuredName", "unstructuredName" },
11020
    { WC_NID_name, WC_NAME_NAME_OID, oidCsrAttrType, "name", "name" },
11021
    { WC_NID_surname, SURNAME_OID,
11022
        oidCsrAttrType, "surname", "surname" },
11023
    { WC_NID_givenName, WC_NAME_GIVEN_NAME_OID,
11024
        oidCsrAttrType, "givenName", "givenName" },
11025
    { WC_NID_initials, WC_NAME_INITIALIS_OID,
11026
        oidCsrAttrType, "initials", "initials" },
11027
    { WC_NID_dnQualifier, DNQUALIFIER_OID,
11028
        oidCsrAttrType, "dnQualifer", "dnQualifier" },
11029
#endif
11030
#endif
11031
#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */
11032
        /* oidHashType */
11033
    #ifdef WOLFSSL_MD2
11034
        { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"},
11035
    #endif
11036
    #ifndef NO_MD4
11037
        { WC_NID_md4, MD4h, oidHashType, "MD4", "md4"},
11038
    #endif
11039
    #ifndef NO_MD5
11040
        { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"},
11041
    #endif
11042
    #ifndef NO_SHA
11043
        { WC_NID_sha1, SHAh, oidHashType, "SHA1", "sha1"},
11044
    #endif
11045
    #ifdef WOLFSSL_SHA224
11046
        { WC_NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"},
11047
    #endif
11048
    #ifndef NO_SHA256
11049
        { WC_NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"},
11050
    #endif
11051
    #ifdef WOLFSSL_SHA384
11052
        { WC_NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"},
11053
    #endif
11054
    #ifdef WOLFSSL_SHA512
11055
        { WC_NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"},
11056
    #endif
11057
    #ifdef WOLFSSL_SHA3
11058
        #ifndef WOLFSSL_NOSHA3_224
11059
        { WC_NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"},
11060
        #endif
11061
        #ifndef WOLFSSL_NOSHA3_256
11062
        { WC_NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"},
11063
        #endif
11064
        #ifndef WOLFSSL_NOSHA3_384
11065
        { WC_NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"},
11066
        #endif
11067
        #ifndef WOLFSSL_NOSHA3_512
11068
        { WC_NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"},
11069
        #endif
11070
    #endif /* WOLFSSL_SHA3 */
11071
    #ifdef WOLFSSL_SM3
11072
        { WC_NID_sm3, SM3h, oidHashType, "SM3", "sm3"},
11073
    #endif
11074
    #ifdef WOLFSSL_SHAKE128
11075
        { WC_NID_shake128, SHAKE128h, oidHashType, "SHAKE128", "shake128"},
11076
    #endif
11077
    #ifdef WOLFSSL_SHAKE256
11078
        { WC_NID_shake256, SHAKE256h, oidHashType, "SHAKE256", "shake256"},
11079
    #endif
11080
        /* oidSigType */
11081
    #ifndef NO_DSA
11082
        #ifndef NO_SHA
11083
        { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType,
11084
          "DSA-SHA1", "dsaWithSHA1"},
11085
        { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256",
11086
          "dsa_with_SHA256"},
11087
        #endif
11088
    #endif /* NO_DSA */
11089
    #ifndef NO_RSA
11090
        #ifdef WOLFSSL_MD2
11091
        { WC_NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2",
11092
          "md2WithRSAEncryption"},
11093
        #endif
11094
        #ifndef NO_MD5
11095
        { WC_NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5",
11096
          "md5WithRSAEncryption"},
11097
        #endif
11098
        #ifndef NO_SHA
11099
        { WC_NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1",
11100
          "sha1WithRSAEncryption"},
11101
        #endif
11102
        #ifdef WOLFSSL_SHA224
11103
        { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType,
11104
          "RSA-SHA224", "sha224WithRSAEncryption"},
11105
        #endif
11106
        #ifndef NO_SHA256
11107
        { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType,
11108
          "RSA-SHA256", "sha256WithRSAEncryption"},
11109
        #endif
11110
        #ifdef WOLFSSL_SHA384
11111
        { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType,
11112
          "RSA-SHA384", "sha384WithRSAEncryption"},
11113
        #endif
11114
        #ifdef WOLFSSL_SHA512
11115
        { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType,
11116
          "RSA-SHA512", "sha512WithRSAEncryption"},
11117
        #endif
11118
        #ifdef WOLFSSL_SHA3
11119
        #ifndef WOLFSSL_NOSHA3_224
11120
        { WC_NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224",
11121
          "sha3-224WithRSAEncryption"},
11122
        #endif
11123
        #ifndef WOLFSSL_NOSHA3_256
11124
        { WC_NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256",
11125
          "sha3-256WithRSAEncryption"},
11126
        #endif
11127
        #ifndef WOLFSSL_NOSHA3_384
11128
        { WC_NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384",
11129
          "sha3-384WithRSAEncryption"},
11130
        #endif
11131
        #ifndef WOLFSSL_NOSHA3_512
11132
        { WC_NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512",
11133
          "sha3-512WithRSAEncryption"},
11134
        #endif
11135
        #endif
11136
        #ifdef WC_RSA_PSS
11137
        { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType,
11138
          "RSASSA-PSS", "rsassaPss" },
11139
        #endif
11140
    #endif /* NO_RSA */
11141
    #ifdef HAVE_ECC
11142
        #ifndef NO_SHA
11143
        { WC_NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1",
11144
          "shaWithECDSA"},
11145
        #endif
11146
        #ifdef WOLFSSL_SHA224
11147
        { WC_NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType,
11148
          "ecdsa-with-SHA224","sha224WithECDSA"},
11149
        #endif
11150
        #ifndef NO_SHA256
11151
        { WC_NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType,
11152
          "ecdsa-with-SHA256","sha256WithECDSA"},
11153
        #endif
11154
        #ifdef WOLFSSL_SHA384
11155
        { WC_NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType,
11156
          "ecdsa-with-SHA384","sha384WithECDSA"},
11157
        #endif
11158
        #ifdef WOLFSSL_SHA512
11159
        { WC_NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType,
11160
          "ecdsa-with-SHA512","sha512WithECDSA"},
11161
        #endif
11162
        #ifdef WOLFSSL_SHA3
11163
        #ifndef WOLFSSL_NOSHA3_224
11164
        { WC_NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType,
11165
          "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"},
11166
        #endif
11167
        #ifndef WOLFSSL_NOSHA3_256
11168
        { WC_NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType,
11169
          "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"},
11170
        #endif
11171
        #ifndef WOLFSSL_NOSHA3_384
11172
        { WC_NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType,
11173
          "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"},
11174
        #endif
11175
        #ifndef WOLFSSL_NOSHA3_512
11176
        { WC_NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType,
11177
          "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"},
11178
        #endif
11179
        #endif
11180
    #endif /* HAVE_ECC */
11181
11182
        /* oidKeyType */
11183
    #ifndef NO_DSA
11184
        { WC_NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"},
11185
    #endif /* NO_DSA */
11186
    #ifndef NO_RSA
11187
        { WC_NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption",
11188
          "rsaEncryption"},
11189
    #ifdef WC_RSA_PSS
11190
        { WC_NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"},
11191
    #endif
11192
    #endif /* NO_RSA */
11193
    #ifdef HAVE_ECC
11194
        { WC_NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey",
11195
                                                        "id-ecPublicKey"},
11196
    #endif /* HAVE_ECC */
11197
    #ifndef NO_DH
11198
        { WC_NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement",
11199
          "dhKeyAgreement"},
11200
    #endif
11201
    #ifdef HAVE_ED448
11202
        { WC_NID_ED448, ED448k,  oidKeyType, "ED448", "ED448"},
11203
    #endif
11204
    #ifdef HAVE_ED25519
11205
        { WC_NID_ED25519, ED25519k,  oidKeyType, "ED25519", "ED25519"},
11206
    #endif
11207
    #ifdef HAVE_FALCON
11208
        { CTC_FALCON_LEVEL1, FALCON_LEVEL1k,  oidKeyType, "Falcon Level 1",
11209
                                                          "Falcon Level 1"},
11210
        { CTC_FALCON_LEVEL5, FALCON_LEVEL5k,  oidKeyType, "Falcon Level 5",
11211
                                                          "Falcon Level 5"},
11212
    #endif /* HAVE_FALCON */
11213
    #ifdef WOLFSSL_HAVE_MLDSA
11214
    #ifdef WOLFSSL_MLDSA_FIPS204_DRAFT
11215
        /* Pre-standardization (NIST PQC round 3) Dilithium OID labels.
11216
         * These coexist with the FIPS 204 "ML-DSA 44/65/87" entries below
11217
         * and are intentionally kept under the Dilithium name. */
11218
        { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k,  oidKeyType,
11219
          "Dilithium Level 2", "Dilithium Level 2"},
11220
        { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k,  oidKeyType,
11221
          "Dilithium Level 3", "Dilithium Level 3"},
11222
        { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k,  oidKeyType,
11223
          "Dilithium Level 5", "Dilithium Level 5"},
11224
    #endif /* WOLFSSL_MLDSA_FIPS204_DRAFT */
11225
        { CTC_ML_DSA_44, ML_DSA_44k,  oidKeyType,
11226
          "ML-DSA 44", "ML-DSA 44"},
11227
        { CTC_ML_DSA_65, ML_DSA_65k,  oidKeyType,
11228
          "ML-DSA 65", "ML-DSA 65"},
11229
        { CTC_ML_DSA_87, ML_DSA_87k,  oidKeyType,
11230
          "ML-DSA 87", "ML-DSA 87"},
11231
    #endif /* WOLFSSL_HAVE_MLDSA */
11232
11233
        /* oidCurveType */
11234
    #ifdef HAVE_ECC
11235
        { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType,
11236
          "prime192v1", "prime192v1"},
11237
        { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType,
11238
          "prime192v2", "prime192v2"},
11239
        { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType,
11240
          "prime192v3", "prime192v3"},
11241
11242
        { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType,
11243
          "prime239v1", "prime239v1"},
11244
        { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType,
11245
          "prime239v2", "prime239v2"},
11246
        { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType,
11247
          "prime239v3", "prime239v3"},
11248
11249
        { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType,
11250
          "prime256v1", "prime256v1"},
11251
11252
        { WC_NID_secp112r1, ECC_SECP112R1_OID,  oidCurveType, "secp112r1",
11253
          "secp112r1"},
11254
        { WC_NID_secp112r2, ECC_SECP112R2_OID,  oidCurveType, "secp112r2",
11255
          "secp112r2"},
11256
11257
        { WC_NID_secp128r1, ECC_SECP128R1_OID,  oidCurveType, "secp128r1",
11258
          "secp128r1"},
11259
        { WC_NID_secp128r2, ECC_SECP128R2_OID,  oidCurveType, "secp128r2",
11260
          "secp128r2"},
11261
11262
        { WC_NID_secp160r1, ECC_SECP160R1_OID,  oidCurveType, "secp160r1",
11263
          "secp160r1"},
11264
        { WC_NID_secp160r2, ECC_SECP160R2_OID,  oidCurveType, "secp160r2",
11265
          "secp160r2"},
11266
11267
        { WC_NID_secp224r1, ECC_SECP224R1_OID,  oidCurveType, "secp224r1",
11268
          "secp224r1"},
11269
        { WC_NID_secp384r1, ECC_SECP384R1_OID,  oidCurveType, "secp384r1",
11270
          "secp384r1"},
11271
        { WC_NID_secp521r1, ECC_SECP521R1_OID,  oidCurveType, "secp521r1",
11272
          "secp521r1"},
11273
11274
        { WC_NID_secp160k1, ECC_SECP160K1_OID,  oidCurveType, "secp160k1",
11275
          "secp160k1"},
11276
        { WC_NID_secp192k1, ECC_SECP192K1_OID,  oidCurveType, "secp192k1",
11277
          "secp192k1"},
11278
        { WC_NID_secp224k1, ECC_SECP224K1_OID,  oidCurveType, "secp224k1",
11279
          "secp224k1"},
11280
        { WC_NID_secp256k1, ECC_SECP256K1_OID,  oidCurveType, "secp256k1",
11281
          "secp256k1"},
11282
11283
        { WC_NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID,  oidCurveType,
11284
          "brainpoolP160r1", "brainpoolP160r1"},
11285
        { WC_NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID,  oidCurveType,
11286
          "brainpoolP192r1", "brainpoolP192r1"},
11287
        { WC_NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID,  oidCurveType,
11288
          "brainpoolP224r1", "brainpoolP224r1"},
11289
        { WC_NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID,  oidCurveType,
11290
          "brainpoolP256r1", "brainpoolP256r1"},
11291
        { WC_NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID,  oidCurveType,
11292
          "brainpoolP320r1", "brainpoolP320r1"},
11293
        { WC_NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID,  oidCurveType,
11294
          "brainpoolP384r1", "brainpoolP384r1"},
11295
        { WC_NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID,  oidCurveType,
11296
          "brainpoolP512r1", "brainpoolP512r1"},
11297
11298
    #ifdef WOLFSSL_SM2
11299
        { WC_NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"},
11300
    #endif
11301
    #endif /* HAVE_ECC */
11302
11303
        /* oidBlkType */
11304
    #ifdef WOLFSSL_AES_128
11305
        { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"},
11306
    #endif
11307
    #ifdef WOLFSSL_AES_192
11308
        { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"},
11309
    #endif
11310
    #ifdef WOLFSSL_AES_256
11311
        { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"},
11312
    #endif
11313
    #ifndef NO_DES3
11314
        { WC_NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"},
11315
        { WC_NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"},
11316
    #endif /* !NO_DES3 */
11317
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
11318
        { WC_NID_chacha20_poly1305, WC_NID_chacha20_poly1305, oidBlkType,
11319
          "ChaCha20-Poly1305", "chacha20-poly1305"},
11320
    #endif
11321
11322
        /* oidOcspType */
11323
    #ifdef HAVE_OCSP
11324
        { WC_NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType,
11325
          "basicOCSPResponse", "Basic OCSP Response"},
11326
        { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"},
11327
    #endif /* HAVE_OCSP */
11328
11329
    #ifndef NO_PWDBASED
11330
        /* oidKdfType */
11331
        { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"},
11332
11333
        /* oidPBEType */
11334
        { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType,
11335
          "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"},
11336
        { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES",
11337
          "pbeWithSHA1AndDES-CBC"},
11338
        { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES",
11339
          "pbeWithSHA1And3-KeyTripleDES-CBC"},
11340
    #endif
11341
11342
        /* oidKeyWrapType */
11343
    #ifdef WOLFSSL_AES_128
11344
        { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap",
11345
          "aes128-wrap"},
11346
    #endif
11347
    #ifdef WOLFSSL_AES_192
11348
        { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap",
11349
          "aes192-wrap"},
11350
    #endif
11351
    #ifdef WOLFSSL_AES_256
11352
        { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap",
11353
          "aes256-wrap"},
11354
    #endif
11355
11356
    #ifndef NO_PKCS7
11357
        #ifndef NO_DH
11358
        /* oidCmsKeyAgreeType */
11359
            #ifndef NO_SHA
11360
        { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme,
11361
          oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme",
11362
          "dhSinglePass-stdDH-sha1kdf-scheme"},
11363
            #endif
11364
            #ifdef WOLFSSL_SHA224
11365
        { dhSinglePass_stdDH_sha224kdf_scheme,
11366
          dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType,
11367
          "dhSinglePass-stdDH-sha224kdf-scheme",
11368
          "dhSinglePass-stdDH-sha224kdf-scheme"},
11369
            #endif
11370
            #ifndef NO_SHA256
11371
        { dhSinglePass_stdDH_sha256kdf_scheme,
11372
          dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType,
11373
          "dhSinglePass-stdDH-sha256kdf-scheme",
11374
          "dhSinglePass-stdDH-sha256kdf-scheme"},
11375
            #endif
11376
            #ifdef WOLFSSL_SHA384
11377
        { dhSinglePass_stdDH_sha384kdf_scheme,
11378
          dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType,
11379
          "dhSinglePass-stdDH-sha384kdf-scheme",
11380
          "dhSinglePass-stdDH-sha384kdf-scheme"},
11381
            #endif
11382
            #ifdef WOLFSSL_SHA512
11383
        { dhSinglePass_stdDH_sha512kdf_scheme,
11384
          dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType,
11385
          "dhSinglePass-stdDH-sha512kdf-scheme",
11386
          "dhSinglePass-stdDH-sha512kdf-scheme"},
11387
            #endif
11388
        #endif
11389
    #endif
11390
    #if defined(WOLFSSL_APACHE_HTTPD)
11391
        /* "1.3.6.1.5.5.7.8.7" */
11392
        { WC_NID_id_on_dnsSRV, WOLFSSL_DNS_SRV_SUM, oidCertNameType,
11393
            WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV },
11394
11395
        /* "1.3.6.1.4.1.311.20.2.3" */
11396
        { WC_NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN,
11397
            WOLFSSL_LN_MS_UPN },
11398
11399
        /* "1.3.6.1.5.5.7.1.24" */
11400
        { WC_NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType,
11401
            WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE },
11402
    #endif
11403
#endif /* OPENSSL_EXTRA */
11404
};
11405
11406
#define WOLFSSL_OBJECT_INFO_SZ \
11407
                (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info))
11408
const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ;
11409
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11410
11411
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
11412
/* Free the dynamically allocated data.
11413
 *
11414
 * p  Pointer to dynamically allocated memory.
11415
 */
11416
void wolfSSL_OPENSSL_free(void* p)
11417
{
11418
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
11419
11420
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
11421
}
11422
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11423
11424
#ifdef OPENSSL_EXTRA
11425
11426
void *wolfSSL_OPENSSL_malloc(size_t a)
11427
{
11428
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
11429
}
11430
11431
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
11432
{
11433
    /* 'char' is unsigned on some platforms. */
11434
    return (int)(signed char)HexCharToByte((char)c);
11435
}
11436
11437
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
11438
{
11439
    unsigned char* targetBuf;
11440
    int srcDigitHigh = 0;
11441
    int srcDigitLow = 0;
11442
    size_t srcLen;
11443
    size_t srcIdx = 0;
11444
    long targetIdx = 0;
11445
11446
    srcLen = XSTRLEN(str);
11447
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
11448
    if (targetBuf == NULL) {
11449
        return NULL;
11450
    }
11451
11452
    while (srcIdx < srcLen) {
11453
        if (str[srcIdx] == ':') {
11454
            srcIdx++;
11455
            continue;
11456
        }
11457
11458
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
11459
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
11460
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
11461
            WOLFSSL_MSG("Invalid hex character.");
11462
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
11463
            return NULL;
11464
        }
11465
11466
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
11467
                                                  srcDigitLow       );
11468
    }
11469
11470
    if (len != NULL)
11471
        *len = targetIdx;
11472
11473
    return targetBuf;
11474
}
11475
11476
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
11477
{
11478
    (void)opts;
11479
    (void)settings;
11480
    return wolfSSL_library_init();
11481
}
11482
11483
int wolfSSL_OPENSSL_init_crypto(word64 opts,
11484
    const WOLFSSL_INIT_SETTINGS* settings)
11485
{
11486
    (void)opts;
11487
    (void)settings;
11488
    return wolfSSL_library_init();
11489
}
11490
11491
#endif /* OPENSSL_EXTRA */
11492
11493
11494
#ifdef HAVE_FUZZER
11495
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
11496
{
11497
    if (ssl) {
11498
        ssl->fuzzerCb  = cbf;
11499
        ssl->fuzzerCtx = fCtx;
11500
    }
11501
}
11502
#endif
11503
11504
#ifndef NO_CERTS
11505
#ifdef  HAVE_PK_CALLBACKS
11506
11507
/* callback for premaster secret generation */
11508
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
11509
{
11510
    if (ctx)
11511
        ctx->GenPreMasterCb = cb;
11512
}
11513
/* Set premaster secret generation callback context */
11514
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
11515
{
11516
    if (ssl)
11517
        ssl->GenPreMasterCtx = ctx;
11518
}
11519
/* Get premaster secret generation callback context */
11520
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
11521
{
11522
    if (ssl)
11523
        return ssl->GenPreMasterCtx;
11524
11525
    return NULL;
11526
}
11527
11528
/* callback for master secret generation */
11529
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
11530
    CallbackGenMasterSecret cb)
11531
{
11532
    if (ctx)
11533
        ctx->GenMasterCb = cb;
11534
}
11535
/* Set master secret generation callback context */
11536
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
11537
{
11538
    if (ssl)
11539
        ssl->GenMasterCtx = ctx;
11540
}
11541
/* Get master secret generation callback context */
11542
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
11543
{
11544
    if (ssl)
11545
        return ssl->GenMasterCtx;
11546
11547
    return NULL;
11548
}
11549
11550
/* callback for extended master secret generation */
11551
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
11552
    CallbackGenExtMasterSecret cb)
11553
{
11554
    if (ctx)
11555
        ctx->GenExtMasterCb = cb;
11556
}
11557
/* Set extended master secret generation callback context */
11558
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
11559
{
11560
    if (ssl)
11561
        ssl->GenExtMasterCtx = ctx;
11562
}
11563
/* Get extended master secret generation callback context */
11564
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
11565
{
11566
    if (ssl)
11567
        return ssl->GenExtMasterCtx;
11568
11569
    return NULL;
11570
}
11571
11572
11573
/* callback for session key generation */
11574
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
11575
{
11576
    if (ctx)
11577
        ctx->GenSessionKeyCb = cb;
11578
}
11579
/* Set session key generation callback context */
11580
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
11581
{
11582
    if (ssl)
11583
        ssl->GenSessionKeyCtx = ctx;
11584
}
11585
/* Get session key generation callback context */
11586
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
11587
{
11588
    if (ssl)
11589
        return ssl->GenSessionKeyCtx;
11590
11591
    return NULL;
11592
}
11593
11594
/* callback for setting encryption keys */
11595
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
11596
{
11597
    if (ctx)
11598
        ctx->EncryptKeysCb = cb;
11599
}
11600
/* Set encryption keys callback context */
11601
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
11602
{
11603
    if (ssl)
11604
        ssl->EncryptKeysCtx = ctx;
11605
}
11606
/* Get encryption keys callback context */
11607
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
11608
{
11609
    if (ssl)
11610
        return ssl->EncryptKeysCtx;
11611
11612
    return NULL;
11613
}
11614
11615
/* callback for Tls finished */
11616
/* the callback can be used to build TLS Finished message if enabled */
11617
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
11618
{
11619
    if (ctx)
11620
        ctx->TlsFinishedCb = cb;
11621
}
11622
/* Set Tls finished callback context */
11623
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
11624
{
11625
    if (ssl)
11626
        ssl->TlsFinishedCtx = ctx;
11627
}
11628
/* Get Tls finished callback context */
11629
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
11630
{
11631
    if (ssl)
11632
        return ssl->TlsFinishedCtx;
11633
11634
    return NULL;
11635
}
11636
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
11637
/* callback for verify data */
11638
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
11639
{
11640
    if (ctx)
11641
        ctx->VerifyMacCb = cb;
11642
}
11643
11644
/* Set set keys callback context */
11645
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
11646
{
11647
    if (ssl)
11648
        ssl->VerifyMacCtx = ctx;
11649
}
11650
/* Get set  keys callback context */
11651
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
11652
{
11653
    if (ssl)
11654
        return ssl->VerifyMacCtx;
11655
11656
    return NULL;
11657
}
11658
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
11659
11660
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
11661
                                      CallbackHKDFExpandLabel cb)
11662
{
11663
    if (ctx)
11664
        ctx->HKDFExpandLabelCb = cb;
11665
}
11666
#ifdef WOLFSSL_PUBLIC_ASN
11667
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
11668
                                        CallbackProcessPeerCert cb)
11669
{
11670
    if (ctx)
11671
        ctx->ProcessPeerCertCb = cb;
11672
}
11673
#endif /* WOLFSSL_PUBLIC_ASN */
11674
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
11675
                                       CallbackProcessServerSigKex cb)
11676
{
11677
    if (ctx)
11678
        ctx->ProcessServerSigKexCb = cb;
11679
}
11680
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
11681
                                          CallbackPerformTlsRecordProcessing cb)
11682
{
11683
    if (ctx)
11684
        ctx->PerformTlsRecordProcessingCb = cb;
11685
}
11686
#endif /* HAVE_PK_CALLBACKS */
11687
#endif /* NO_CERTS */
11688
11689
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
11690
11691
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
11692
{
11693
    if (ctx)
11694
        ctx->HkdfExtractCb = cb;
11695
}
11696
11697
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
11698
{
11699
    if (ssl)
11700
        ssl->HkdfExtractCtx = ctx;
11701
}
11702
11703
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
11704
{
11705
    if (ssl)
11706
        return ssl->HkdfExtractCtx;
11707
11708
    return NULL;
11709
}
11710
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
11711
11712
#ifdef WOLFSSL_HAVE_WOLFSCEP
11713
    /* Used by autoconf to see if wolfSCEP is available */
11714
    void wolfSSL_wolfSCEP(void) {}
11715
#endif
11716
11717
11718
#ifdef WOLFSSL_HAVE_CERT_SERVICE
11719
    /* Used by autoconf to see if cert service is available */
11720
    void wolfSSL_cert_service(void) {}
11721
#endif
11722
11723
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
11724
    !defined(WOLFCRYPT_ONLY)
11725
11726
    /* NID variables are dependent on compatibility header files currently
11727
     *
11728
     * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL
11729
     *         on fail
11730
     */
11731
11732
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id)
11733
    {
11734
        return wolfSSL_OBJ_nid2obj_ex(id, NULL);
11735
    }
11736
11737
11738
    WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id,
11739
                                                WOLFSSL_ASN1_OBJECT* arg_obj)
11740
    {
11741
        word32 oidSz = 0;
11742
        int nid = 0;
11743
        const byte* oid;
11744
        word32 type = 0;
11745
        WOLFSSL_ASN1_OBJECT* obj = arg_obj;
11746
        byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */
11747
        word32 objSz = 0;
11748
        const char* sName = NULL;
11749
        int i;
11750
11751
#ifdef WOLFSSL_DEBUG_OPENSSL
11752
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj");
11753
#endif
11754
11755
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
11756
            if (wolfssl_object_info[i].nid == id) {
11757
                nid = id;
11758
                id = wolfssl_object_info[i].id;
11759
                sName = wolfssl_object_info[i].sName;
11760
                type = wolfssl_object_info[i].type;
11761
                break;
11762
            }
11763
        }
11764
        if (i == (int)WOLFSSL_OBJECT_INFO_SZ) {
11765
            WOLFSSL_MSG("NID not in table");
11766
        #ifdef WOLFSSL_QT
11767
            sName = NULL;
11768
            type = (word32)id;
11769
        #else
11770
            return NULL;
11771
        #endif
11772
        }
11773
11774
    #ifdef HAVE_ECC
11775
         if (type == 0 && wc_ecc_get_oid((word32)id, &oid, &oidSz) > 0) {
11776
             type = oidCurveType;
11777
         }
11778
    #endif /* HAVE_ECC */
11779
11780
        if (sName != NULL) {
11781
            if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) {
11782
                WOLFSSL_MSG("Attempted short name is too large");
11783
                return NULL;
11784
            }
11785
        }
11786
11787
        oid = OidFromId((word32)id, type, &oidSz);
11788
11789
        /* set object ID to buffer */
11790
        if (obj == NULL){
11791
            obj = wolfSSL_ASN1_OBJECT_new();
11792
            if (obj == NULL) {
11793
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
11794
                return NULL;
11795
            }
11796
        }
11797
        obj->nid     = nid;
11798
        obj->type    = id;
11799
        obj->grp     = (int)type;
11800
11801
        obj->sName[0] = '\0';
11802
        if (sName != NULL) {
11803
            XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName));
11804
        }
11805
11806
        objBuf[0] = ASN_OBJECT_ID; objSz++;
11807
        objSz += SetLength(oidSz, objBuf + 1);
11808
        if (oidSz) {
11809
            XMEMCPY(objBuf + objSz, oid, oidSz);
11810
            objSz     += oidSz;
11811
        }
11812
11813
        if (obj->objSz == 0 || objSz != obj->objSz) {
11814
            obj->objSz = objSz;
11815
            if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) ||
11816
                                                           (obj->obj == NULL)) {
11817
                if (obj->obj != NULL)
11818
                    XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1);
11819
                obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
11820
                if (obj->obj == NULL) {
11821
                    wolfSSL_ASN1_OBJECT_free(obj);
11822
                    return NULL;
11823
                }
11824
                obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
11825
            }
11826
            else {
11827
                obj->dynamic &= (unsigned char)~WOLFSSL_ASN1_DYNAMIC_DATA;
11828
            }
11829
        }
11830
        XMEMCPY((byte*)obj->obj, objBuf, obj->objSz);
11831
11832
        (void)type;
11833
11834
        return obj;
11835
    }
11836
11837
    static const char* oid_translate_num_to_str(const char* oid)
11838
    {
11839
        const struct oid_dict {
11840
            const char* num;
11841
            const char* desc;
11842
        } oid_dict[] = {
11843
            { "2.5.29.37.0",       "Any Extended Key Usage" },
11844
            { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" },
11845
            { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" },
11846
            { "1.3.6.1.5.5.7.3.3", "Code Signing" },
11847
            { "1.3.6.1.5.5.7.3.4", "E-mail Protection" },
11848
            { "1.3.6.1.5.5.7.3.8", "Time Stamping" },
11849
            { "1.3.6.1.5.5.7.3.9", "OCSP Signing" },
11850
            { NULL, NULL }
11851
        };
11852
        const struct oid_dict* idx;
11853
11854
        for (idx = oid_dict; idx->num != NULL; idx++) {
11855
            if (!XSTRCMP(oid, idx->num)) {
11856
                return idx->desc;
11857
            }
11858
        }
11859
        return NULL;
11860
    }
11861
11862
    static int wolfssl_obj2txt_numeric(char *buf, int bufLen,
11863
                                       const WOLFSSL_ASN1_OBJECT *a)
11864
    {
11865
        int bufSz;
11866
        int    length;
11867
        word32 idx = 0;
11868
        byte   tag;
11869
11870
        if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) {
11871
            return WOLFSSL_FAILURE;
11872
        }
11873
11874
        if (tag != ASN_OBJECT_ID) {
11875
            WOLFSSL_MSG("Bad ASN1 Object");
11876
            return WOLFSSL_FAILURE;
11877
        }
11878
11879
        if (GetLength((const byte*)a->obj, &idx, &length,
11880
                       a->objSz) < 0 || length < 0) {
11881
            return ASN_PARSE_E;
11882
        }
11883
11884
        if (bufLen < MAX_OID_STRING_SZ) {
11885
            bufSz = bufLen - 1;
11886
        }
11887
        else {
11888
            bufSz = MAX_OID_STRING_SZ;
11889
        }
11890
11891
        if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx,
11892
                    (word32)length)) <= 0) {
11893
            WOLFSSL_MSG("Error decoding OID");
11894
            return WOLFSSL_FAILURE;
11895
        }
11896
11897
        buf[bufSz] = '\0';
11898
11899
        return bufSz;
11900
    }
11901
11902
    /* If no_name is one then use numerical form, otherwise short name.
11903
     *
11904
     * Returns the buffer size on success, WOLFSSL_FAILURE on error
11905
     */
11906
    int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a,
11907
                            int no_name)
11908
    {
11909
        int bufSz;
11910
        const char* desc;
11911
        const char* name;
11912
11913
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt");
11914
11915
        if (buf == NULL || bufLen <= 1 || a == NULL) {
11916
            WOLFSSL_MSG("Bad input argument");
11917
            return WOLFSSL_FAILURE;
11918
        }
11919
11920
        if (no_name == 1) {
11921
            return wolfssl_obj2txt_numeric(buf, bufLen, a);
11922
        }
11923
11924
        /* return long name unless using x509small, then return short name */
11925
#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA)
11926
        name = a->sName;
11927
#else
11928
        name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a));
11929
#endif
11930
11931
        if (name == NULL) {
11932
            WOLFSSL_MSG("Name not found");
11933
            bufSz = 0;
11934
        }
11935
        else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) {
11936
            bufSz = (int)XSTRLEN(name);
11937
        }
11938
        else {
11939
            bufSz = bufLen - 1;
11940
        }
11941
        if (bufSz) {
11942
            XMEMCPY(buf, name, (size_t)bufSz);
11943
        }
11944
        else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL ||
11945
                 a->type == WOLFSSL_GEN_URI) {
11946
            size_t objLen = XSTRLEN((const char*)a->obj);
11947
            if (objLen >= (size_t)bufLen) {
11948
                bufSz = bufLen - 1;
11949
            }
11950
            else {
11951
                bufSz = (int)objLen;
11952
            }
11953
            XMEMCPY(buf, a->obj, (size_t)bufSz);
11954
        }
11955
        else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) {
11956
            if ((desc = oid_translate_num_to_str(buf))) {
11957
                bufSz = (int)XSTRLEN(desc);
11958
                bufSz = (int)min((word32)bufSz,(word32) bufLen - 1);
11959
                XMEMCPY(buf, desc, (size_t)bufSz);
11960
            }
11961
        }
11962
        else {
11963
            bufSz = 0;
11964
        }
11965
11966
        buf[bufSz] = '\0';
11967
11968
        return bufSz;
11969
    }
11970
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
11971
11972
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
11973
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
11974
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
11975
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL)
11976
    /* Returns the long name that corresponds with an ASN1_OBJECT nid value.
11977
     *  n : NID value of ASN1_OBJECT to search */
11978
    const char* wolfSSL_OBJ_nid2ln(int n)
11979
    {
11980
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
11981
        size_t i;
11982
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln");
11983
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
11984
            if (obj_info->nid == n) {
11985
                return obj_info->lName;
11986
            }
11987
        }
11988
        WOLFSSL_MSG("NID not found in table");
11989
        return NULL;
11990
    }
11991
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
11992
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */
11993
11994
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
11995
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
11996
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
11997
    defined(WOLFSSL_HAPROXY)
11998
    /* Return the corresponding short name for the nid <n>.
11999
     * or NULL if short name can't be found.
12000
     */
12001
    const char * wolfSSL_OBJ_nid2sn(int n) {
12002
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
12003
        size_t i;
12004
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn");
12005
12006
        if (n == WC_NID_md5) {
12007
            /* WC_NID_surname == WC_NID_md5 and WC_NID_surname comes before WC_NID_md5 in
12008
             * wolfssl_object_info. As a result, the loop below will incorrectly
12009
             * return "SN" instead of "MD5." WC_NID_surname isn't the true OpenSSL
12010
             * NID, but other functions rely on this table and modifying it to
12011
             * conform with OpenSSL's NIDs isn't trivial. */
12012
             return "MD5";
12013
        }
12014
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
12015
            if (obj_info->nid == n) {
12016
                return obj_info->sName;
12017
            }
12018
        }
12019
        WOLFSSL_MSG_EX("SN not found (nid:%d)",n);
12020
        return NULL;
12021
    }
12022
12023
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12024
    int wolfSSL_OBJ_sn2nid(const char *sn) {
12025
        WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid");
12026
        if (sn == NULL)
12027
            return WC_NID_undef;
12028
        return wc_OBJ_sn2nid(sn);
12029
    }
12030
#endif
12031
12032
    size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o)
12033
    {
12034
        size_t ret = 0;
12035
        int err = 0;
12036
        word32 idx = 0;
12037
        int len = 0;
12038
12039
        WOLFSSL_ENTER("wolfSSL_OBJ_length");
12040
12041
        if (o == NULL || o->obj == NULL) {
12042
            WOLFSSL_MSG("Bad argument.");
12043
            err = 1;
12044
        }
12045
12046
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
12047
            WOLFSSL_MSG("Error parsing ASN.1 header.");
12048
            err = 1;
12049
        }
12050
        if (err == 0) {
12051
            ret = (size_t)len;
12052
        }
12053
12054
        WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret);
12055
12056
        return ret;
12057
    }
12058
12059
    const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o)
12060
    {
12061
        const unsigned char* ret = NULL;
12062
        int err = 0;
12063
        word32 idx = 0;
12064
        int len = 0;
12065
12066
        WOLFSSL_ENTER("wolfSSL_OBJ_get0_data");
12067
12068
        if (o == NULL || o->obj == NULL) {
12069
            WOLFSSL_MSG("Bad argument.");
12070
            err = 1;
12071
        }
12072
12073
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
12074
            WOLFSSL_MSG("Error parsing ASN.1 header.");
12075
            err = 1;
12076
        }
12077
        if (err == 0) {
12078
            ret = o->obj + idx;
12079
        }
12080
12081
        return ret;
12082
    }
12083
12084
12085
    /* Gets the NID value that corresponds with the ASN1 object.
12086
     *
12087
     * o ASN1 object to get NID of
12088
     *
12089
     * Return NID on success and a negative value on failure
12090
     */
12091
    int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o)
12092
    {
12093
        word32 oid = 0;
12094
        word32 idx = 0;
12095
        int ret;
12096
12097
#ifdef WOLFSSL_DEBUG_OPENSSL
12098
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid");
12099
#endif
12100
12101
        if (o == NULL) {
12102
            return WOLFSSL_FATAL_ERROR;
12103
        }
12104
12105
        #ifdef WOLFSSL_QT
12106
        if (o->grp == oidCertExtType) {
12107
            /* If nid is an unknown extension, return WC_NID_undef */
12108
            if (wolfSSL_OBJ_nid2sn(o->nid) == NULL)
12109
                return WC_NID_undef;
12110
        }
12111
        #endif
12112
12113
        if (o->nid > 0)
12114
            return o->nid;
12115
        if ((ret = GetObjectId(o->obj, &idx, &oid,
12116
                                    (word32)o->grp, o->objSz)) < 0) {
12117
            if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) {
12118
                /* Put ASN object tag in front and try again */
12119
                int len = SetObjectId((int)o->objSz, NULL) + (int)o->objSz;
12120
                byte* buf = (byte*)XMALLOC((size_t)len, NULL,
12121
                                            DYNAMIC_TYPE_TMP_BUFFER);
12122
                if (!buf) {
12123
                    WOLFSSL_MSG("malloc error");
12124
                    return WOLFSSL_FATAL_ERROR;
12125
                }
12126
                idx = (word32)SetObjectId((int)o->objSz, buf);
12127
                XMEMCPY(buf + idx, o->obj, o->objSz);
12128
                idx = 0;
12129
                ret = GetObjectId(buf, &idx, &oid, (word32)o->grp, (word32)len);
12130
                XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
12131
                if (ret < 0) {
12132
                    WOLFSSL_MSG("Issue getting OID of object");
12133
                    return WOLFSSL_FATAL_ERROR;
12134
                }
12135
            }
12136
            else {
12137
                WOLFSSL_MSG("Issue getting OID of object");
12138
                return WOLFSSL_FATAL_ERROR;
12139
            }
12140
        }
12141
12142
        return oid2nid(oid, o->grp);
12143
    }
12144
12145
    /* Return the corresponding NID for the long name <ln>
12146
     * or WC_NID_undef if NID can't be found.
12147
     */
12148
    int wolfSSL_OBJ_ln2nid(const char *ln)
12149
    {
12150
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
12151
        size_t lnlen;
12152
        WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid");
12153
        if (ln && (lnlen = XSTRLEN(ln)) > 0) {
12154
            /* Accept input like "/commonName=" */
12155
            if (ln[0] == '/') {
12156
                ln++;
12157
                lnlen--;
12158
            }
12159
            if (lnlen) {
12160
                size_t i;
12161
12162
                if (ln[lnlen-1] == '=') {
12163
                    lnlen--;
12164
                }
12165
                for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
12166
                    if (lnlen == XSTRLEN(obj_info->lName) &&
12167
                            XSTRNCMP(ln, obj_info->lName, lnlen) == 0) {
12168
                        return obj_info->nid;
12169
                    }
12170
                }
12171
            }
12172
        }
12173
        return WC_NID_undef;
12174
    }
12175
12176
    /* compares two objects, return 0 if equal */
12177
    int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a,
12178
                        const WOLFSSL_ASN1_OBJECT* b)
12179
    {
12180
        WOLFSSL_ENTER("wolfSSL_OBJ_cmp");
12181
12182
        if (a && b && a->obj && b->obj) {
12183
            if (a->objSz == b->objSz) {
12184
                return XMEMCMP(a->obj, b->obj, a->objSz);
12185
            }
12186
            else if (a->type == EXT_KEY_USAGE_OID ||
12187
                     b->type == EXT_KEY_USAGE_OID) {
12188
                /* Special case for EXT_KEY_USAGE_OID so that
12189
                 * cmp will be treated as a substring search */
12190
                /* Used in libest to check for id-kp-cmcRA in
12191
                 * EXT_KEY_USAGE extension */
12192
                unsigned int idx;
12193
                const byte* s; /* shorter */
12194
                unsigned int sLen;
12195
                const byte* l; /* longer */
12196
                unsigned int lLen;
12197
                if (a->objSz > b->objSz) {
12198
                    s = b->obj; sLen = b->objSz;
12199
                    l = a->obj; lLen = a->objSz;
12200
                }
12201
                else {
12202
                    s = a->obj; sLen = a->objSz;
12203
                    l = b->obj; lLen = b->objSz;
12204
                }
12205
                for (idx = 0; idx <= lLen - sLen; idx++) {
12206
                    if (XMEMCMP(l + idx, s, sLen) == 0) {
12207
                        /* Found substring */
12208
                        return 0;
12209
                    }
12210
                }
12211
            }
12212
        }
12213
12214
        return WOLFSSL_FATAL_ERROR;
12215
    }
12216
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
12217
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */
12218
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
12219
    defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
12220
    defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
12221
    defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
12222
    /* Gets the NID value that is related to the OID string passed in. Example
12223
     * string would be "2.5.29.14" for subject key ID.
12224
     *
12225
     * returns NID value on success and WC_NID_undef on error
12226
     */
12227
    int wolfSSL_OBJ_txt2nid(const char* s)
12228
    {
12229
        unsigned int i;
12230
    #ifdef WOLFSSL_CERT_EXT
12231
        int ret;
12232
        unsigned int sum = 0;
12233
        unsigned int outSz = MAX_OID_SZ;
12234
        unsigned char out[MAX_OID_SZ];
12235
12236
        XMEMSET(out, 0, sizeof(out));
12237
    #endif
12238
12239
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid");
12240
12241
        if (s == NULL) {
12242
            return WC_NID_undef;
12243
        }
12244
12245
    #ifdef WOLFSSL_CERT_EXT
12246
        ret = EncodePolicyOID(out, &outSz, s, NULL);
12247
        if (ret == 0) {
12248
            /* sum OID */
12249
            sum = wc_oid_sum(out, outSz);
12250
        }
12251
    #endif /* WOLFSSL_CERT_EXT */
12252
12253
        /* get the group that the OID's sum is in
12254
         * @TODO possible conflict with multiples */
12255
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
12256
            int len;
12257
        #ifdef WOLFSSL_CERT_EXT
12258
            if (ret == 0) {
12259
                if (wolfssl_object_info[i].id == (int)sum) {
12260
                    return wolfssl_object_info[i].nid;
12261
                }
12262
            }
12263
        #endif
12264
12265
            /* try as a short name */
12266
            len = (int)XSTRLEN(s);
12267
            if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len &&
12268
                XSTRNCMP(wolfssl_object_info[i].sName, s, (word32)len) == 0) {
12269
                return wolfssl_object_info[i].nid;
12270
            }
12271
12272
            /* try as a long name */
12273
            if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len &&
12274
                XSTRNCMP(wolfssl_object_info[i].lName, s, (word32)len) == 0) {
12275
                return wolfssl_object_info[i].nid;
12276
            }
12277
        }
12278
12279
        return WC_NID_undef;
12280
    }
12281
#endif
12282
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
12283
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
12284
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
12285
    defined(WOLFSSL_HAPROXY)
12286
12287
    /* Creates new ASN1_OBJECT from short name, long name, or text
12288
     * representation of oid. If no_name is 0, then short name, long name, and
12289
     * numerical value of oid are interpreted. If no_name is 1, then only the
12290
     * numerical value of the oid is interpreted.
12291
     *
12292
     * Returns pointer to ASN1_OBJECT on success, or NULL on error.
12293
     */
12294
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
12295
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name)
12296
    {
12297
        int i, ret;
12298
        int nid = WC_NID_undef;
12299
        unsigned int outSz = MAX_OID_SZ;
12300
        unsigned char out[MAX_OID_SZ];
12301
        WOLFSSL_ASN1_OBJECT* obj;
12302
12303
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj");
12304
12305
        if (s == NULL)
12306
            return NULL;
12307
12308
        /* If s is numerical value, try to sum oid */
12309
        ret = EncodePolicyOID(out, &outSz, s, NULL);
12310
        if (ret == 0 && outSz > 0) {
12311
            /* If numerical encode succeeded then just
12312
             * create object from that because sums are
12313
             * not unique and can cause confusion. */
12314
            obj = wolfSSL_ASN1_OBJECT_new();
12315
            if (obj == NULL) {
12316
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
12317
                return NULL;
12318
            }
12319
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
12320
            obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL,
12321
                    DYNAMIC_TYPE_ASN1);
12322
            if (obj->obj == NULL) {
12323
                wolfSSL_ASN1_OBJECT_free(obj);
12324
                return NULL;
12325
            }
12326
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
12327
            i = SetObjectId((int)outSz, (byte*)obj->obj);
12328
            XMEMCPY((byte*)obj->obj + i, out, outSz);
12329
            obj->objSz = (word32)i + outSz;
12330
            return obj;
12331
        }
12332
12333
        /* TODO: update short names in wolfssl_object_info and check OID sums
12334
           are correct */
12335
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
12336
            /* Short name, long name, and numerical value are interpreted */
12337
            if (no_name == 0 &&
12338
                ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) ||
12339
                 (XSTRCMP(s, wolfssl_object_info[i].lName) == 0)))
12340
            {
12341
                    nid = wolfssl_object_info[i].nid;
12342
            }
12343
        }
12344
12345
        if (nid != WC_NID_undef)
12346
            return wolfSSL_OBJ_nid2obj(nid);
12347
12348
        return NULL;
12349
    }
12350
#endif
12351
12352
    /* compatibility function. Its intended use is to remove OID's from an
12353
     * internal table that have been added with OBJ_create. wolfSSL manages its
12354
     * own internal OID values and does not currently support OBJ_create. */
12355
    void wolfSSL_OBJ_cleanup(void)
12356
    {
12357
        WOLFSSL_ENTER("wolfSSL_OBJ_cleanup");
12358
    }
12359
12360
    #ifndef NO_WOLFSSL_STUB
12361
    int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln)
12362
    {
12363
        (void)oid;
12364
        (void)sn;
12365
        (void)ln;
12366
        WOLFSSL_STUB("wolfSSL_OBJ_create");
12367
        return WOLFSSL_FAILURE;
12368
    }
12369
    #endif
12370
12371
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
12372
    {
12373
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12374
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
12375
        ssl->options.verifyDepth = (byte)depth;
12376
    #endif
12377
    }
12378
12379
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
12380
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
12381
12382
#ifdef OPENSSL_EXTRA
12383
12384
/* wolfSSL uses negative values for error states. This function returns an
12385
 * unsigned type so the value returned is the absolute value of the error.
12386
 */
12387
unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line)
12388
{
12389
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
12390
12391
    (void)line;
12392
    (void)file;
12393
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
12394
    {
12395
        int ret;
12396
12397
        if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) {
12398
            WOLFSSL_MSG("Issue peeking at error node in queue");
12399
            return 0;
12400
        }
12401
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \
12402
        || defined(WOLFSSL_HAPROXY)
12403
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
12404
            return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
12405
    #endif
12406
    #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
12407
        if (ret == ASN1_R_HEADER_TOO_LONG) {
12408
            return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
12409
        }
12410
    #endif
12411
        return (unsigned long)ret;
12412
    }
12413
#else
12414
    return 0;
12415
#endif
12416
}
12417
12418
#endif /* OPENSSL_EXTRA */
12419
12420
#ifdef HAVE_EX_DATA_CRYPTO
12421
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
12422
12423
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
12424
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
12425
        WOLFSSL_CRYPTO_EX_free* free_func)
12426
{
12427
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
12428
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
12429
    if (new_ctx == NULL)
12430
        return WOLFSSL_FATAL_ERROR;
12431
    new_ctx->ctx_l = ctx_l;
12432
    new_ctx->ctx_ptr = ctx_ptr;
12433
    new_ctx->new_func = new_func;
12434
    new_ctx->free_func = free_func;
12435
    new_ctx->dup_func = dup_func;
12436
    new_ctx->next = NULL;
12437
    /* Push to end of list */
12438
    while (*dst != NULL)
12439
        dst = &(*dst)->next;
12440
    *dst = new_ctx;
12441
    return 0;
12442
}
12443
12444
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
12445
{
12446
    while (cb_ctx != NULL) {
12447
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
12448
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
12449
        cb_ctx = next;
12450
    }
12451
}
12452
12453
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
12454
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
12455
{
12456
    int idx = 0;
12457
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12458
        if (cb_ctx->new_func != NULL)
12459
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
12460
                    cb_ctx->ctx_ptr);
12461
    }
12462
}
12463
12464
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
12465
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
12466
{
12467
    int idx = 0;
12468
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12469
        if (cb_ctx->dup_func != NULL) {
12470
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
12471
            if (!cb_ctx->dup_func(out, in,
12472
                    &ptr, idx,
12473
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
12474
                return WOLFSSL_FAILURE;
12475
            }
12476
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
12477
        }
12478
    }
12479
    return WOLFSSL_SUCCESS;
12480
}
12481
12482
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
12483
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
12484
{
12485
    int idx = 0;
12486
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
12487
        if (cb_ctx->free_func != NULL)
12488
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
12489
                    cb_ctx->ctx_ptr);
12490
    }
12491
}
12492
12493
/**
12494
 * wolfssl_local_get_ex_new_index is a helper function for the following
12495
 * xx_get_ex_new_index functions:
12496
 *  - wolfSSL_CRYPTO_get_ex_new_index
12497
 *  - wolfSSL_CTX_get_ex_new_index
12498
 *  - wolfSSL_get_ex_new_index
12499
 * Issues a unique index number for the specified class-index.
12500
 * Returns an index number greater or equal to zero on success,
12501
 * -1 on failure.
12502
 */
12503
int wolfssl_local_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
12504
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
12505
        WOLFSSL_CRYPTO_EX_free* free_func)
12506
{
12507
    /* index counter for each class index*/
12508
    static int ctx_idx = 0;
12509
    static int ssl_idx = 0;
12510
    static int ssl_session_idx = 0;
12511
    static int x509_idx = 0;
12512
12513
    int idx = -1;
12514
12515
    switch(class_index) {
12516
        case WOLF_CRYPTO_EX_INDEX_SSL:
12517
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12518
                    dup_func, free_func);
12519
            idx = ssl_idx++;
12520
            break;
12521
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
12522
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12523
                    dup_func, free_func);
12524
            idx = ctx_idx++;
12525
            break;
12526
        case WOLF_CRYPTO_EX_INDEX_X509:
12527
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
12528
                    dup_func, free_func);
12529
            idx = x509_idx++;
12530
            break;
12531
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
12532
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
12533
                    new_func, dup_func, free_func) != 0)
12534
                return WOLFSSL_FATAL_ERROR;
12535
            idx = ssl_session_idx++;
12536
            break;
12537
12538
        /* following class indexes are not supoprted */
12539
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
12540
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
12541
        case WOLF_CRYPTO_EX_INDEX_DH:
12542
        case WOLF_CRYPTO_EX_INDEX_DSA:
12543
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
12544
        case WOLF_CRYPTO_EX_INDEX_RSA:
12545
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
12546
        case WOLF_CRYPTO_EX_INDEX_UI:
12547
        case WOLF_CRYPTO_EX_INDEX_BIO:
12548
        case WOLF_CRYPTO_EX_INDEX_APP:
12549
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
12550
        case WOLF_CRYPTO_EX_INDEX_DRBG:
12551
        default:
12552
            break;
12553
    }
12554
    if (idx >= MAX_EX_DATA)
12555
        return WOLFSSL_FATAL_ERROR;
12556
    return idx;
12557
}
12558
#endif /* HAVE_EX_DATA_CRYPTO */
12559
12560
#ifdef HAVE_EX_DATA_CRYPTO
12561
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
12562
                                 WOLFSSL_CRYPTO_EX_new* new_func,
12563
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
12564
                                 WOLFSSL_CRYPTO_EX_free* free_func)
12565
{
12566
12567
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
12568
12569
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx,
12570
                                    arg, new_func, dup_func, free_func);
12571
}
12572
12573
/* Return the index that can be used for the WOLFSSL structure to store
12574
 * application data.
12575
 *
12576
 */
12577
int wolfSSL_get_ex_new_index(long argValue, void* arg,
12578
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
12579
        WOLFSSL_CRYPTO_EX_free* cb3)
12580
{
12581
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
12582
12583
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue,
12584
            arg, cb1, cb2, cb3);
12585
}
12586
#endif /* HAVE_EX_DATA_CRYPTO */
12587
12588
#ifdef OPENSSL_EXTRA
12589
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
12590
{
12591
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
12592
#ifdef HAVE_EX_DATA
12593
    if (ctx != NULL) {
12594
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
12595
    }
12596
#else
12597
    (void)ctx;
12598
    (void)idx;
12599
#endif
12600
    return NULL;
12601
}
12602
12603
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
12604
{
12605
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
12606
#ifdef HAVE_EX_DATA
12607
    if (ctx != NULL) {
12608
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
12609
    }
12610
#else
12611
    (void)ctx;
12612
    (void)idx;
12613
    (void)data;
12614
#endif
12615
    return WOLFSSL_FAILURE;
12616
}
12617
12618
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
12619
int wolfSSL_CTX_set_ex_data_with_cleanup(
12620
    WOLFSSL_CTX* ctx,
12621
    int idx,
12622
    void* data,
12623
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
12624
{
12625
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
12626
    if (ctx != NULL) {
12627
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
12628
                                                       cleanup_routine);
12629
    }
12630
    return WOLFSSL_FAILURE;
12631
}
12632
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
12633
#endif /* OPENSSL_EXTRA */
12634
12635
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12636
12637
/* Returns char* to app data stored in ex[0].
12638
 *
12639
 * ssl WOLFSSL structure to get app data from
12640
 */
12641
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
12642
{
12643
    /* checkout exdata stuff... */
12644
    WOLFSSL_ENTER("wolfSSL_get_app_data");
12645
12646
    return wolfSSL_get_ex_data(ssl, 0);
12647
}
12648
12649
12650
/* Set ex array 0 to have app data
12651
 *
12652
 * ssl WOLFSSL struct to set app data in
12653
 * arg data to be stored
12654
 *
12655
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
12656
 */
12657
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
12658
    WOLFSSL_ENTER("wolfSSL_set_app_data");
12659
12660
    return wolfSSL_set_ex_data(ssl, 0, arg);
12661
}
12662
12663
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
12664
12665
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
12666
0
{
12667
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
12668
#ifdef HAVE_EX_DATA
12669
    if (ssl != NULL) {
12670
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
12671
    }
12672
#else
12673
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
12674
0
    (void)ssl;
12675
0
    (void)idx;
12676
0
    (void)data;
12677
0
#endif
12678
0
    return WOLFSSL_FAILURE;
12679
0
}
12680
12681
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
12682
int wolfSSL_set_ex_data_with_cleanup(
12683
    WOLFSSL* ssl,
12684
    int idx,
12685
    void* data,
12686
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
12687
{
12688
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
12689
    if (ssl != NULL)
12690
    {
12691
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
12692
                                                       cleanup_routine);
12693
    }
12694
    return WOLFSSL_FAILURE;
12695
}
12696
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
12697
12698
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
12699
0
{
12700
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
12701
#ifdef HAVE_EX_DATA
12702
    if (ssl != NULL) {
12703
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
12704
    }
12705
#else
12706
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
12707
0
    (void)ssl;
12708
0
    (void)idx;
12709
0
#endif
12710
0
    return 0;
12711
0
}
12712
12713
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
12714
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
12715
12716
/* returns the enum value associated with handshake state
12717
 *
12718
 * ssl the WOLFSSL structure to get state of
12719
 */
12720
int wolfSSL_get_state(const WOLFSSL* ssl)
12721
{
12722
    WOLFSSL_ENTER("wolfSSL_get_state");
12723
12724
    if (ssl == NULL) {
12725
        WOLFSSL_MSG("Null argument passed in");
12726
        return WOLFSSL_FAILURE;
12727
    }
12728
12729
    return ssl->options.handShakeState;
12730
}
12731
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
12732
12733
#ifdef OPENSSL_EXTRA
12734
void wolfSSL_certs_clear(WOLFSSL* ssl)
12735
{
12736
    WOLFSSL_ENTER("wolfSSL_certs_clear");
12737
12738
    if (ssl == NULL)
12739
        return;
12740
12741
    /* ctx still owns certificate, certChain, key, dh, and cm */
12742
    if (ssl->buffers.weOwnCert) {
12743
        FreeDer(&ssl->buffers.certificate);
12744
        ssl->buffers.weOwnCert = 0;
12745
    }
12746
    ssl->buffers.certificate = NULL;
12747
    if (ssl->buffers.weOwnCertChain) {
12748
        FreeDer(&ssl->buffers.certChain);
12749
        ssl->buffers.weOwnCertChain = 0;
12750
    }
12751
    ssl->buffers.certChain = NULL;
12752
#ifdef WOLFSSL_TLS13
12753
    ssl->buffers.certChainCnt = 0;
12754
#endif
12755
    if (ssl->buffers.weOwnKey) {
12756
        FreeDer(&ssl->buffers.key);
12757
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12758
        FreeDer(&ssl->buffers.keyMask);
12759
    #endif
12760
        ssl->buffers.weOwnKey = 0;
12761
    }
12762
    ssl->buffers.key      = NULL;
12763
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12764
    ssl->buffers.keyMask  = NULL;
12765
#endif
12766
    ssl->buffers.keyType  = 0;
12767
    ssl->buffers.keyId    = 0;
12768
    ssl->buffers.keyLabel = 0;
12769
    ssl->buffers.keySz    = 0;
12770
    ssl->buffers.keyDevId = 0;
12771
#ifdef WOLFSSL_DUAL_ALG_CERTS
12772
    if (ssl->buffers.weOwnAltKey) {
12773
        FreeDer(&ssl->buffers.altKey);
12774
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12775
        FreeDer(&ssl->buffers.altKeyMask);
12776
    #endif
12777
        ssl->buffers.weOwnAltKey = 0;
12778
    }
12779
    ssl->buffers.altKey     = NULL;
12780
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12781
    ssl->buffers.altKeyMask = NULL;
12782
#endif
12783
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12784
}
12785
#endif
12786
12787
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
12788
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
12789
12790
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
12791
{
12792
    WOLFSSL_ENTER("wolfSSL_ctrl");
12793
    if (ssl == NULL)
12794
        return BAD_FUNC_ARG;
12795
12796
    switch (cmd) {
12797
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
12798
            defined(OPENSSL_ALL)
12799
        #ifdef HAVE_SNI
12800
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
12801
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
12802
            if (pt == NULL) {
12803
                WOLFSSL_MSG("Passed in NULL Host Name.");
12804
                break;
12805
            }
12806
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
12807
        #endif /* HAVE_SNI */
12808
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
12809
        default:
12810
            WOLFSSL_MSG("Case not implemented.");
12811
    }
12812
    (void)opt;
12813
    (void)pt;
12814
    return WOLFSSL_FAILURE;
12815
}
12816
12817
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
12818
{
12819
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
12820
    long ctrl_opt;
12821
#endif
12822
    long ret = WOLFSSL_SUCCESS;
12823
12824
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
12825
    if (ctx == NULL)
12826
        return WOLFSSL_FAILURE;
12827
12828
    switch (cmd) {
12829
    case SSL_CTRL_CHAIN:
12830
#ifdef SESSION_CERTS
12831
    {
12832
        /*
12833
         * We don't care about opt here because a copy of the certificate is
12834
         * stored anyway so increasing the reference counter is not necessary.
12835
         * Just check to make sure that it is set to one of the correct values.
12836
         */
12837
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
12838
        WOLFSSL_X509* x509;
12839
        int i;
12840
        if (opt != 0 && opt != 1) {
12841
            ret = WOLFSSL_FAILURE;
12842
            break;
12843
        }
12844
        /* Clear certificate chain */
12845
        FreeDer(&ctx->certChain);
12846
        if (sk) {
12847
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
12848
                x509 = wolfSSL_sk_X509_value(sk, i);
12849
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
12850
                if (wolfSSL_X509_up_ref(x509) != 1) {
12851
                    WOLFSSL_MSG("Error increasing reference count");
12852
                    continue;
12853
                }
12854
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
12855
                        WOLFSSL_SUCCESS) {
12856
                    WOLFSSL_MSG("Error adding certificate to context");
12857
                    /* Decrease reference count on failure */
12858
                    wolfSSL_X509_free(x509);
12859
                    x509 = NULL;
12860
                }
12861
            }
12862
        }
12863
        /* Free previous chain */
12864
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
12865
        ctx->x509Chain = sk;
12866
        if (sk && opt == 1) {
12867
            /* up all refs when opt == 1 */
12868
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
12869
                x509 = wolfSSL_sk_X509_value(sk, i);
12870
                if (wolfSSL_X509_up_ref(x509) != 1) {
12871
                    WOLFSSL_MSG("Error increasing reference count");
12872
                    continue;
12873
                }
12874
            }
12875
        }
12876
    }
12877
#else
12878
        WOLFSSL_MSG("Session certificates not compiled in");
12879
        ret = WOLFSSL_FAILURE;
12880
#endif
12881
        break;
12882
12883
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
12884
    case SSL_CTRL_OPTIONS:
12885
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
12886
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
12887
12888
        #ifdef WOLFSSL_QT
12889
        /* Set whether to use client or server cipher preference */
12890
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
12891
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
12892
            WOLFSSL_MSG("Using Server's Cipher Preference.");
12893
            ctx->useClientOrder = 0;
12894
        } else {
12895
            WOLFSSL_MSG("Using Client's Cipher Preference.");
12896
            ctx->useClientOrder = 1;
12897
        }
12898
        #endif /* WOLFSSL_QT */
12899
12900
        return ctrl_opt;
12901
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
12902
    case SSL_CTRL_EXTRA_CHAIN_CERT:
12903
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
12904
        if (pt == NULL) {
12905
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
12906
            ret = WOLFSSL_FAILURE;
12907
            break;
12908
        }
12909
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
12910
12911
#ifndef NO_DH
12912
    case SSL_CTRL_SET_TMP_DH:
12913
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
12914
        if (pt == NULL) {
12915
            WOLFSSL_MSG("Passed in DH pointer NULL.");
12916
            ret = WOLFSSL_FAILURE;
12917
            break;
12918
        }
12919
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
12920
#endif
12921
12922
#ifdef HAVE_ECC
12923
    case SSL_CTRL_SET_TMP_ECDH:
12924
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
12925
        if (pt == NULL) {
12926
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
12927
            ret = WOLFSSL_FAILURE;
12928
            break;
12929
        }
12930
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
12931
#endif
12932
    case SSL_CTRL_MODE:
12933
        wolfSSL_CTX_set_mode(ctx,opt);
12934
        break;
12935
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
12936
        WOLFSSL_MSG("set min proto version");
12937
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
12938
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
12939
        WOLFSSL_MSG("set max proto version");
12940
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
12941
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
12942
        WOLFSSL_MSG("get min proto version");
12943
        return wolfSSL_CTX_get_min_proto_version(ctx);
12944
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
12945
        WOLFSSL_MSG("get max proto version");
12946
        return wolfSSL_CTX_get_max_proto_version(ctx);
12947
    default:
12948
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
12949
        ret = WOLFSSL_FAILURE;
12950
        break;
12951
    }
12952
12953
    (void)ctx;
12954
    (void)cmd;
12955
    (void)opt;
12956
    (void)pt;
12957
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
12958
    return ret;
12959
}
12960
12961
#ifndef NO_WOLFSSL_STUB
12962
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
12963
{
12964
    (void) ctx;
12965
    (void) cmd;
12966
    (void) fp;
12967
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
12968
    return WOLFSSL_FAILURE;
12969
12970
}
12971
#endif /* NO_WOLFSSL_STUB */
12972
12973
12974
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
12975
12976
12977
/* stunnel compatibility functions*/
12978
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
12979
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
12980
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
12981
     defined(WOLFSSL_OPENSSH)))
12982
void wolfSSL_ERR_remove_thread_state(void* pid)
12983
{
12984
    (void) pid;
12985
    return;
12986
}
12987
12988
#ifndef NO_FILESYSTEM
12989
/***TBD ***/
12990
void wolfSSL_print_all_errors_fp(XFILE fp)
12991
{
12992
    (void)fp;
12993
}
12994
#endif /* !NO_FILESYSTEM */
12995
12996
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
12997
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
12998
12999
/* Note: This is a huge section of API's - through
13000
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
13001
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
13002
13003
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
13004
    !defined(WOLFSSL_STATIC_MEMORY)
13005
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
13006
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
13007
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
13008
13009
static void* OSSL_Malloc(size_t size)
13010
{
13011
    if (ossl_malloc != NULL)
13012
        return ossl_malloc(size, NULL, 0);
13013
    else
13014
        return NULL;
13015
}
13016
13017
static void  OSSL_Free(void *ptr)
13018
{
13019
    if (ossl_free != NULL)
13020
        ossl_free(ptr, NULL, 0);
13021
}
13022
13023
static void* OSSL_Realloc(void *ptr, size_t size)
13024
{
13025
    if (ossl_realloc != NULL)
13026
        return ossl_realloc(ptr, size, NULL, 0);
13027
    else
13028
        return NULL;
13029
}
13030
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
13031
        * !WOLFSSL_STATIC_MEMORY */
13032
13033
int wolfSSL_CRYPTO_set_mem_functions(
13034
        wolfSSL_OSSL_Malloc_cb  m,
13035
        wolfSSL_OSSL_Realloc_cb r,
13036
        wolfSSL_OSSL_Free_cb    f)
13037
{
13038
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
13039
#ifdef WOLFSSL_DEBUG_MEMORY
13040
    WOLFSSL_MSG("mem functions will receive function name instead of "
13041
                "file name");
13042
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
13043
            (wolfSSL_Realloc_cb)r) == 0)
13044
        return WOLFSSL_SUCCESS;
13045
#else
13046
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
13047
                "functions will receive a NULL file name and 0 for the "
13048
                "line number.");
13049
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
13050
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
13051
        ossl_malloc = m;
13052
        ossl_free = f;
13053
        ossl_realloc = r;
13054
        return WOLFSSL_SUCCESS;
13055
    }
13056
#endif
13057
    else
13058
        return WOLFSSL_FAILURE;
13059
#else
13060
    (void)m;
13061
    (void)r;
13062
    (void)f;
13063
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
13064
    return WOLFSSL_FAILURE;
13065
#endif
13066
}
13067
13068
int wolfSSL_ERR_load_ERR_strings(void)
13069
{
13070
    return WOLFSSL_SUCCESS;
13071
}
13072
13073
void wolfSSL_ERR_load_crypto_strings(void)
13074
{
13075
    WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings");
13076
    /* Do nothing */
13077
    return;
13078
}
13079
13080
int wolfSSL_FIPS_mode(void)
13081
{
13082
#ifdef HAVE_FIPS
13083
    return 1;
13084
#else
13085
    return 0;
13086
#endif
13087
}
13088
13089
int wolfSSL_FIPS_mode_set(int r)
13090
{
13091
#ifdef HAVE_FIPS
13092
    if (r == 0) {
13093
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
13094
        return WOLFSSL_FAILURE;
13095
    }
13096
    return WOLFSSL_SUCCESS;
13097
#else
13098
    if (r == 0) {
13099
        return WOLFSSL_SUCCESS;
13100
    }
13101
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
13102
    return WOLFSSL_FAILURE;
13103
#endif
13104
}
13105
13106
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
13107
{
13108
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
13109
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
13110
13111
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
13112
    (void)alg_bits;
13113
    if (c!= NULL)
13114
        ret = c->bits;
13115
    #else
13116
    if (c != NULL && c->ssl != NULL) {
13117
        ret = 8 * c->ssl->specs.key_size;
13118
        if (alg_bits != NULL) {
13119
            *alg_bits = ret;
13120
        }
13121
    }
13122
    #endif
13123
    return ret;
13124
}
13125
13126
13127
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
13128
{
13129
    int ret;
13130
    /* This method requires some explanation. Its sibling is
13131
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
13132
     * which re-inits the WOLFSSL* with all settings in the new CTX.
13133
     * That one is the right one to use *before* a handshake is started.
13134
     *
13135
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
13136
     * when a server inspects the SNI in a ClientHello callback and
13137
     * decides which set of certificates to use.
13138
     *
13139
     * Since, at the time the SNI callback is run, some decisions on
13140
     * Extensions or the ServerHello might already have been taken, this
13141
     * method is very restricted in what it does:
13142
     * - changing the server certificate(s)
13143
     * - changing the server id for session handling
13144
     * and everything else in WOLFSSL* needs to remain untouched.
13145
     *
13146
     * SECURITY: swapping ssl->ctx switches cm-resolved settings (CA store,
13147
     * CRL, OCSP) to the new CTX but leaves ssl-cached ones (verify mode and
13148
     * callback, minDowngrade, key-size minimums, suites, version bounds)
13149
     * pinned to the original. SNI callbacks must re-apply those ssl-level
13150
     * settings explicitly; CRL/OCSP isolation requires an SSL-local store.
13151
     */
13152
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
13153
    if (ssl == NULL || ctx == NULL)
13154
        return NULL;
13155
    if (ssl->ctx == ctx)
13156
        return ssl->ctx;
13157
13158
    if (ctx->suites == NULL) {
13159
        /* suites */
13160
        if (AllocateCtxSuites(ctx) != 0)
13161
            return NULL;
13162
        InitSSL_CTX_Suites(ctx);
13163
    }
13164
13165
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
13166
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
13167
    if (ret != 0) {
13168
        /* can only fail on serious stuff, like mutex not working
13169
         * or ctx refcount out of whack. */
13170
        return NULL;
13171
    }
13172
#else
13173
    (void)ret;
13174
#endif
13175
    if (ssl->ctx != NULL)
13176
        wolfSSL_CTX_free(ssl->ctx);
13177
    ssl->ctx = ctx;
13178
13179
#ifndef NO_CERTS
13180
#ifdef WOLFSSL_COPY_CERT
13181
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
13182
    if (ctx->certificate != NULL) {
13183
        if (ssl->buffers.certificate != NULL) {
13184
            FreeDer(&ssl->buffers.certificate);
13185
            ssl->buffers.certificate = NULL;
13186
        }
13187
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
13188
            ctx->certificate->length, ctx->certificate->type,
13189
            ctx->certificate->heap);
13190
        if (ret != 0) {
13191
            ssl->buffers.weOwnCert = 0;
13192
            return NULL;
13193
        }
13194
13195
        ssl->buffers.weOwnCert = 1;
13196
    }
13197
    if (ctx->certChain != NULL) {
13198
        if (ssl->buffers.certChain != NULL) {
13199
            FreeDer(&ssl->buffers.certChain);
13200
            ssl->buffers.certChain = NULL;
13201
        }
13202
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
13203
            ctx->certChain->length, ctx->certChain->type,
13204
            ctx->certChain->heap);
13205
        if (ret != 0) {
13206
            ssl->buffers.weOwnCertChain = 0;
13207
            return NULL;
13208
        }
13209
13210
        ssl->buffers.weOwnCertChain = 1;
13211
    }
13212
#else
13213
    /* ctx owns certificate, certChain and key */
13214
    ssl->buffers.certificate = ctx->certificate;
13215
    ssl->buffers.certChain = ctx->certChain;
13216
#endif
13217
#ifdef WOLFSSL_TLS13
13218
    ssl->buffers.certChainCnt = ctx->certChainCnt;
13219
#endif
13220
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
13221
#ifdef WOLFSSL_COPY_KEY
13222
    if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
13223
        FreeDer(&ssl->buffers.key);
13224
    }
13225
    if (ctx->privateKey != NULL) {
13226
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
13227
            ctx->privateKey->length, ctx->privateKey->type,
13228
            ctx->privateKey->heap);
13229
        if (ret != 0) {
13230
            ssl->buffers.weOwnKey = 0;
13231
            return NULL;
13232
        }
13233
        ssl->buffers.weOwnKey = 1;
13234
    }
13235
    else {
13236
        ssl->buffers.key      = ctx->privateKey;
13237
    }
13238
#else
13239
    ssl->buffers.key      = ctx->privateKey;
13240
#endif
13241
#else
13242
    if (ctx->privateKey != NULL) {
13243
        if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
13244
            FreeDer(&ssl->buffers.key);
13245
        }
13246
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
13247
            ctx->privateKey->length, ctx->privateKey->type,
13248
            ctx->privateKey->heap);
13249
        if (ret != 0) {
13250
            return NULL;
13251
        }
13252
        /* Blind the private key for the SSL with new random mask. */
13253
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
13254
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
13255
            &ssl->buffers.keyMask);
13256
        if (ret != 0) {
13257
            return NULL;
13258
        }
13259
    }
13260
#endif
13261
    ssl->buffers.keyType  = ctx->privateKeyType;
13262
    ssl->buffers.keyId    = ctx->privateKeyId;
13263
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
13264
    ssl->buffers.keySz    = ctx->privateKeySz;
13265
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
13266
    /* flags indicating what certs/keys are available */
13267
    ssl->options.haveRSA          = ctx->haveRSA;
13268
    ssl->options.haveDH           = ctx->haveDH;
13269
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
13270
    ssl->options.haveECC          = ctx->haveECC;
13271
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
13272
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
13273
    ssl->options.haveMlDsaSig = ctx->haveMlDsaSig;
13274
#ifdef WOLFSSL_DUAL_ALG_CERTS
13275
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
13276
    ssl->buffers.altKey   = ctx->altPrivateKey;
13277
#else
13278
    if (ctx->altPrivateKey != NULL) {
13279
        ret = AllocCopyDer(&ssl->buffers.altKey, ctx->altPrivateKey->buffer,
13280
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
13281
            ctx->altPrivateKey->heap);
13282
        if (ret != 0) {
13283
            return NULL;
13284
        }
13285
        /* Blind the private key for the SSL with new random mask. */
13286
        wolfssl_priv_der_blind_toggle(ssl->buffers.altKey,
13287
                                      ctx->altPrivateKeyMask);
13288
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
13289
            &ssl->buffers.altKeyMask);
13290
        if (ret != 0) {
13291
            return NULL;
13292
        }
13293
    }
13294
#endif
13295
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
13296
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
13297
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13298
#endif
13299
13300
#ifdef WOLFSSL_SESSION_ID_CTX
13301
    /* copy over application session context ID */
13302
    ssl->sessionCtxSz = ctx->sessionCtxSz;
13303
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
13304
#endif
13305
13306
    return ssl->ctx;
13307
}
13308
13309
13310
#ifndef NO_BIO
13311
void wolfSSL_ERR_load_BIO_strings(void) {
13312
    WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings");
13313
    /* do nothing */
13314
}
13315
#endif
13316
13317
#ifndef NO_WOLFSSL_STUB
13318
/* Set THREADID callback, return 1 on success, 0 on error */
13319
int wolfSSL_THREADID_set_callback(
13320
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
13321
{
13322
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
13323
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
13324
    (void)threadid_func;
13325
    return 1;
13326
}
13327
#endif
13328
13329
#ifndef NO_WOLFSSL_STUB
13330
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
13331
{
13332
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
13333
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
13334
    (void)id;
13335
    (void)val;
13336
    return;
13337
}
13338
#endif
13339
13340
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
13341
13342
13343
#if defined(OPENSSL_EXTRA)
13344
13345
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
13346
{
13347
    int ret = 0;
13348
    int chunk;
13349
    const byte* pa = (const byte*)a;
13350
    const byte* pb = (const byte*)b;
13351
13352
    if (!a || !b)
13353
        return -1;
13354
    /* ConstantCompare takes an int length. Compare in chunks of at most
13355
     * INT_MAX so a size that does not fit in an int is not narrowed into a
13356
     * negative or truncated length, which could wrongly report equality. */
13357
    while (size > 0) {
13358
        chunk = (size > (size_t)INT_MAX) ? INT_MAX : (int)size;
13359
        ret |= ConstantCompare(pa, pb, chunk);
13360
        pa += chunk;
13361
        pb += chunk;
13362
        size -= (size_t)chunk;
13363
    }
13364
    return ret;
13365
}
13366
13367
unsigned long wolfSSL_ERR_peek_last_error(void)
13368
{
13369
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
13370
13371
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
13372
    {
13373
        int ret;
13374
13375
        if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) {
13376
            WOLFSSL_MSG("Issue peeking at error node in queue");
13377
            return 0;
13378
        }
13379
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
13380
            return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
13381
    #if defined(WOLFSSL_PYTHON)
13382
        if (ret == ASN1_R_HEADER_TOO_LONG)
13383
            return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
13384
    #endif
13385
        return (unsigned long)ret;
13386
    }
13387
#else
13388
    return 0;
13389
#endif
13390
}
13391
13392
#endif /* OPENSSL_EXTRA */
13393
13394
int wolfSSL_version(WOLFSSL* ssl)
13395
0
{
13396
0
    WOLFSSL_ENTER("wolfSSL_version");
13397
0
    if (ssl->version.major == SSLv3_MAJOR) {
13398
0
        switch (ssl->version.minor) {
13399
0
            case SSLv3_MINOR :
13400
0
                return SSL3_VERSION;
13401
0
            case TLSv1_MINOR :
13402
0
                return TLS1_VERSION;
13403
0
            case TLSv1_1_MINOR :
13404
0
                return TLS1_1_VERSION;
13405
0
            case TLSv1_2_MINOR :
13406
0
                return TLS1_2_VERSION;
13407
0
            case TLSv1_3_MINOR :
13408
0
                return TLS1_3_VERSION;
13409
0
            default:
13410
0
                return WOLFSSL_FAILURE;
13411
0
        }
13412
0
    }
13413
0
    else if (ssl->version.major == DTLS_MAJOR) {
13414
0
        switch (ssl->version.minor) {
13415
0
            case DTLS_MINOR :
13416
0
                return DTLS1_VERSION;
13417
0
            case DTLSv1_2_MINOR :
13418
0
                return DTLS1_2_VERSION;
13419
0
            case DTLSv1_3_MINOR:
13420
0
                return DTLS1_3_VERSION;
13421
0
            default:
13422
0
                return WOLFSSL_FAILURE;
13423
0
        }
13424
0
    }
13425
0
    return WOLFSSL_FAILURE;
13426
0
}
13427
13428
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
13429
0
{
13430
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
13431
0
    return ssl->ctx;
13432
0
}
13433
13434
13435
#ifdef WOLFSSL_JNI
13436
13437
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
13438
{
13439
    WOLFSSL_ENTER("wolfSSL_set_jobject");
13440
    if (ssl != NULL)
13441
    {
13442
        ssl->jObjectRef = objPtr;
13443
        return WOLFSSL_SUCCESS;
13444
    }
13445
    return WOLFSSL_FAILURE;
13446
}
13447
13448
void* wolfSSL_get_jobject(WOLFSSL* ssl)
13449
{
13450
    WOLFSSL_ENTER("wolfSSL_get_jobject");
13451
    if (ssl != NULL)
13452
        return ssl->jObjectRef;
13453
    return NULL;
13454
}
13455
13456
#endif /* WOLFSSL_JNI */
13457
13458
13459
#ifdef WOLFSSL_ASYNC_CRYPT
13460
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
13461
    WOLF_EVENT_FLAG flags, int* eventCount)
13462
{
13463
    if (ctx == NULL) {
13464
        return BAD_FUNC_ARG;
13465
    }
13466
13467
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
13468
                                        events, maxEvents, flags, eventCount);
13469
}
13470
13471
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
13472
{
13473
    int ret, eventCount = 0;
13474
    WOLF_EVENT* events[1];
13475
13476
    if (ssl == NULL) {
13477
        return BAD_FUNC_ARG;
13478
    }
13479
13480
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
13481
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
13482
    if (ret == 0) {
13483
        ret = eventCount;
13484
    }
13485
13486
    return ret;
13487
}
13488
#endif /* WOLFSSL_ASYNC_CRYPT */
13489
13490
#ifdef OPENSSL_EXTRA
13491
13492
static int peek_ignore_err(int err)
13493
{
13494
  switch(err) {
13495
    case -WC_NO_ERR_TRACE(WANT_READ):
13496
    case -WC_NO_ERR_TRACE(WANT_WRITE):
13497
    case -WC_NO_ERR_TRACE(ZERO_RETURN):
13498
    case -WOLFSSL_ERROR_ZERO_RETURN:
13499
    case -WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E):
13500
    case -WC_NO_ERR_TRACE(SOCKET_ERROR_E):
13501
      return 1;
13502
    default:
13503
      return 0;
13504
  }
13505
}
13506
13507
unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line,
13508
                                               const char **data, int *flags)
13509
{
13510
  unsigned long err;
13511
13512
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data");
13513
    err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err);
13514
13515
    if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
13516
        return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
13517
#ifdef OPENSSL_ALL
13518
    /* PARSE_ERROR is returned if an HTTP request is detected. */
13519
    else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR))
13520
        return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */;
13521
#endif
13522
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
13523
    else if (err == ASN1_R_HEADER_TOO_LONG)
13524
        return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
13525
#endif
13526
  return err;
13527
}
13528
#endif
13529
13530
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
13531
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
13532
13533
#if !defined(WOLFSSL_USER_IO)
13534
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
13535
 * example input would be "127.0.0.1" and the returned value would be 7F000001
13536
 */
13537
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
13538
{
13539
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
13540
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
13541
    int  af = WOLFSSL_IP4;
13542
    WOLFSSL_ASN1_STRING *ret = NULL;
13543
13544
    if (ipa == NULL)
13545
        return NULL;
13546
13547
    if (XSTRSTR(ipa, ":") != NULL) {
13548
        af = WOLFSSL_IP6;
13549
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
13550
    }
13551
13552
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
13553
#ifdef FREESCALE_MQX
13554
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
13555
#else
13556
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
13557
#endif
13558
        WOLFSSL_MSG("Error parsing IP address");
13559
        return NULL;
13560
    }
13561
13562
    ret = wolfSSL_ASN1_STRING_new();
13563
    if (ret != NULL) {
13564
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
13565
            WOLFSSL_MSG("Error setting the string");
13566
            wolfSSL_ASN1_STRING_free(ret);
13567
            ret = NULL;
13568
        }
13569
    }
13570
13571
    return ret;
13572
}
13573
#endif /* !WOLFSSL_USER_IO */
13574
13575
/* Is the specified cipher suite a fake one used an an extension proxy? */
13576
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
13577
{
13578
    (void)suite0;
13579
    (void)suite;
13580
#ifdef HAVE_RENEGOTIATION_INDICATION
13581
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
13582
        return 1;
13583
#endif
13584
    return 0;
13585
}
13586
13587
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
13588
        byte suite)
13589
{
13590
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13591
    int cipherSz = GetCipherNamesSize();
13592
    int i;
13593
    for (i = 0; i < cipherSz; i++)
13594
        if (cipher_names[i].cipherSuite0 == suite0 &&
13595
                cipher_names[i].cipherSuite == suite)
13596
            break;
13597
    if (i == cipherSz)
13598
        return 1;
13599
    /* Check min version */
13600
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
13601
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
13602
                cipher_names[i].minor >= TLSv1_MINOR)
13603
            /* 1.0 ciphersuites are in general available in 1.1 and
13604
             * 1.1 ciphersuites are in general available in 1.2 */
13605
            return 0;
13606
        return 1;
13607
    }
13608
    /* Check max version */
13609
    switch (cipher_names[i].minor) {
13610
    case SSLv3_MINOR :
13611
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
13612
    case TLSv1_MINOR :
13613
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
13614
    case TLSv1_1_MINOR :
13615
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
13616
    case TLSv1_2_MINOR :
13617
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
13618
    case TLSv1_3_MINOR :
13619
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
13620
    default:
13621
        WOLFSSL_MSG("Unrecognized minor version");
13622
        return 1;
13623
    }
13624
}
13625
13626
/* returns a pointer to internal cipher suite list. Should not be free'd by
13627
 * caller.
13628
 */
13629
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
13630
{
13631
    const Suites* suites;
13632
#if defined(OPENSSL_ALL)
13633
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13634
    int cipherSz = GetCipherNamesSize();
13635
#endif
13636
13637
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
13638
    if (ssl == NULL)
13639
        return NULL;
13640
13641
    suites = WOLFSSL_SUITES(ssl);
13642
    if (suites == NULL)
13643
        return NULL;
13644
13645
    /* check if stack needs populated */
13646
    if (ssl->suitesStack == NULL) {
13647
        int i;
13648
13649
        ((WOLFSSL*)ssl)->suitesStack =
13650
                wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, ssl->heap);
13651
        if (ssl->suitesStack == NULL)
13652
            return NULL;
13653
13654
        /* higher priority of cipher suite will be on top of stack */
13655
#if defined(OPENSSL_ALL)
13656
        for (i = suites->suiteSz - 2; i >=0; i-=2)
13657
#else
13658
        for (i = 0; i < suites->suiteSz; i+=2)
13659
#endif
13660
        {
13661
            struct WOLFSSL_CIPHER cipher;
13662
13663
            /* A couple of suites are placeholders for special options,
13664
             * skip those. */
13665
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
13666
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
13667
                                            suites->suites[i+1])) {
13668
                continue;
13669
            }
13670
13671
            XMEMSET(&cipher, 0, sizeof(cipher));
13672
            cipher.cipherSuite0 = suites->suites[i];
13673
            cipher.cipherSuite  = suites->suites[i+1];
13674
            cipher.ssl          = ssl;
13675
#if defined(OPENSSL_ALL)
13676
            cipher.in_stack     = 1;
13677
            {
13678
                int j;
13679
                for (j = 0; j < cipherSz; j++) {
13680
                    if (cipher_names[j].cipherSuite0 == cipher.cipherSuite0 &&
13681
                            cipher_names[j].cipherSuite == cipher.cipherSuite) {
13682
                        cipher.offset = (unsigned long)j;
13683
                        break;
13684
                    }
13685
                }
13686
            }
13687
#endif
13688
            if (wolfSSL_sk_insert(ssl->suitesStack, &cipher, 0) <= 0) {
13689
                WOLFSSL_MSG("Error inserting cipher onto stack");
13690
                wolfSSL_sk_CIPHER_free(ssl->suitesStack);
13691
                ((WOLFSSL*)ssl)->suitesStack = NULL;
13692
                break;
13693
            }
13694
        }
13695
13696
        /* If no ciphers were added, free empty stack and return NULL */
13697
        if (ssl->suitesStack != NULL && wolfSSL_sk_num(ssl->suitesStack) == 0) {
13698
            wolfSSL_sk_CIPHER_free(ssl->suitesStack);
13699
            ((WOLFSSL*)ssl)->suitesStack = NULL;
13700
        }
13701
    }
13702
    return ssl->suitesStack;
13703
}
13704
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
13705
#ifdef OPENSSL_ALL
13706
/* returned pointer is to an internal element in WOLFSSL struct and should not
13707
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
13708
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
13709
{
13710
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
13711
    const CipherSuiteInfo* cipher_names = GetCipherNames();
13712
    int cipherSz = GetCipherNamesSize();
13713
    const Suites* suites;
13714
13715
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
13716
13717
    if (ssl == NULL) {
13718
        return NULL;
13719
    }
13720
13721
    /* return NULL if is client side */
13722
    if (wolfSSL_is_server(ssl) == 0) {
13723
        return NULL;
13724
    }
13725
13726
    suites = ssl->clSuites;
13727
    if (suites == NULL) {
13728
        WOLFSSL_MSG("No client suites stored");
13729
    }
13730
    else if (ssl->clSuitesStack != NULL) {
13731
        ret = ssl->clSuitesStack;
13732
    }
13733
    else { /* generate cipher suites stack if not already done */
13734
        int i;
13735
        int j;
13736
13737
        ret = wolfSSL_sk_new_node(ssl->heap);
13738
        if (ret != NULL) {
13739
            ret->type = STACK_TYPE_CIPHER;
13740
13741
            /* higher priority of cipher suite will be on top of stack */
13742
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
13743
                WOLFSSL_CIPHER cipher;
13744
13745
                /* A couple of suites are placeholders for special options,
13746
                 * skip those. */
13747
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
13748
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
13749
                                                suites->suites[i+1])) {
13750
                    continue;
13751
                }
13752
13753
                cipher.cipherSuite0 = suites->suites[i];
13754
                cipher.cipherSuite  = suites->suites[i+1];
13755
                cipher.ssl          = ssl;
13756
                for (j = 0; j < cipherSz; j++) {
13757
                    if (cipher_names[j].cipherSuite0 ==
13758
                            cipher.cipherSuite0 &&
13759
                            cipher_names[j].cipherSuite ==
13760
                                    cipher.cipherSuite) {
13761
                        cipher.offset = (unsigned long)j;
13762
                        break;
13763
                    }
13764
                }
13765
13766
                /* in_stack is checked in wolfSSL_CIPHER_description */
13767
                cipher.in_stack     = 1;
13768
13769
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
13770
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
13771
                    wolfSSL_sk_CIPHER_free(ret);
13772
                    ret = NULL;
13773
                    break;
13774
                }
13775
            }
13776
        }
13777
        ssl->clSuitesStack = ret;
13778
    }
13779
    return ret;
13780
}
13781
#endif /* OPENSSL_ALL */
13782
13783
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
13784
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
13785
{
13786
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
13787
13788
    if (ctx == NULL)
13789
        return 0;
13790
13791
    return ctx->timeout;
13792
}
13793
13794
13795
/* returns the time in seconds of the current timeout */
13796
long wolfSSL_get_timeout(WOLFSSL* ssl)
13797
{
13798
    WOLFSSL_ENTER("wolfSSL_get_timeout");
13799
13800
    if (ssl == NULL)
13801
        return 0;
13802
    return ssl->timeout;
13803
}
13804
#endif
13805
13806
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
13807
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
13808
13809
#ifndef NO_BIO
13810
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
13811
{
13812
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
13813
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
13814
     * The setting buffer size doesn't do anything so return NULL for both.
13815
     */
13816
    if (s == NULL)
13817
        return NULL;
13818
13819
    return s->biord;
13820
}
13821
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
13822
{
13823
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
13824
    (void)s;
13825
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
13826
     * The setting buffer size doesn't do anything so return NULL for both.
13827
     */
13828
    if (s == NULL)
13829
        return NULL;
13830
13831
    return s->biowr;
13832
}
13833
#endif /* !NO_BIO */
13834
13835
#ifndef NO_TLS
13836
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
13837
{
13838
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
13839
    if (s == NULL)
13840
        return WOLFSSL_FAILURE;
13841
13842
    if (s->options.side == WOLFSSL_CLIENT_END) {
13843
    #ifndef NO_WOLFSSL_CLIENT
13844
        return wolfSSL_connect(s);
13845
    #else
13846
        WOLFSSL_MSG("Client not compiled in");
13847
        return WOLFSSL_FAILURE;
13848
    #endif
13849
    }
13850
13851
#ifndef NO_WOLFSSL_SERVER
13852
    return wolfSSL_accept(s);
13853
#else
13854
    WOLFSSL_MSG("Server not compiled in");
13855
    return WOLFSSL_FAILURE;
13856
#endif
13857
}
13858
13859
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
13860
{
13861
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
13862
#ifdef WOLFSSL_QUIC
13863
    if (WOLFSSL_IS_QUIC(s)) {
13864
        return wolfSSL_quic_do_handshake(s);
13865
    }
13866
#endif
13867
    return wolfSSL_SSL_do_handshake_internal(s);
13868
}
13869
#endif /* !NO_TLS */
13870
13871
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
13872
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
13873
#else
13874
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
13875
#endif
13876
{
13877
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
13878
13879
    return !wolfSSL_is_init_finished(ssl);
13880
}
13881
13882
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
13883
{
13884
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
13885
13886
    if (ssl == NULL)
13887
        return WOLFSSL_FAILURE;
13888
13889
    return ssl->options.handShakeState == NULL_STATE;
13890
}
13891
13892
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
13893
{
13894
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
13895
13896
    if (ssl == NULL)
13897
        return WOLFSSL_FAILURE;
13898
13899
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
13900
        return ssl->options.connectState > CONNECT_BEGIN &&
13901
            ssl->options.connectState < SECOND_REPLY_DONE;
13902
    }
13903
13904
    return ssl->options.acceptState > ACCEPT_BEGIN &&
13905
        ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
13906
}
13907
13908
13909
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
13910
    OPENSSL_EXTRA || HAVE_LIGHTY */
13911
13912
13913
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
13914
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
13915
13916
13917
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
13918
{
13919
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
13920
13921
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
13922
}
13923
13924
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
13925
13926
13927
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
13928
13929
#if (defined(HAVE_ECC) || \
13930
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
13931
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
13932
13933
const WOLF_EC_NIST_NAME kNistCurves[] = {
13934
#ifdef HAVE_ECC
13935
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
13936
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
13937
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
13938
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
13939
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
13940
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
13941
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
13942
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
13943
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
13944
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
13945
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
13946
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
13947
     WOLFSSL_ECC_BRAINPOOLP256R1},
13948
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
13949
     WOLFSSL_ECC_BRAINPOOLP384R1},
13950
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
13951
     WOLFSSL_ECC_BRAINPOOLP512R1},
13952
#endif
13953
#ifdef HAVE_CURVE25519
13954
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
13955
#endif
13956
#ifdef HAVE_CURVE448
13957
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
13958
#endif
13959
#ifdef WOLFSSL_HAVE_MLKEM
13960
#ifndef WOLFSSL_NO_ML_KEM
13961
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
13962
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
13963
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
13964
    /* Aliases accepting the OpenSSL/IANA spelling without underscores. */
13965
    {CURVE_NAME("MLKEM512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
13966
    {CURVE_NAME("MLKEM768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
13967
    {CURVE_NAME("MLKEM1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
13968
#if defined(HAVE_ECC)
13969
    #ifdef WOLFSSL_PQC_HYBRIDS
13970
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
13971
     WOLFSSL_SECP256R1MLKEM768},
13972
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
13973
     WOLFSSL_SECP384R1MLKEM1024},
13974
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
13975
     WOLFSSL_X25519MLKEM768},
13976
    #endif /* WOLFSSL_PQC_HYBRIDS */
13977
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
13978
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
13979
     WOLFSSL_SECP256R1MLKEM512},
13980
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
13981
     WOLFSSL_SECP384R1MLKEM768},
13982
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
13983
     WOLFSSL_SECP521R1MLKEM1024},
13984
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
13985
     WOLFSSL_X25519MLKEM512},
13986
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
13987
     WOLFSSL_X448MLKEM768},
13988
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
13989
#endif
13990
#endif /* !WOLFSSL_NO_ML_KEM */
13991
#ifdef WOLFSSL_MLKEM_KYBER
13992
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
13993
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
13994
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
13995
#if defined(HAVE_ECC)
13996
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
13997
     WOLFSSL_P256_KYBER_LEVEL1},
13998
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
13999
     WOLFSSL_P384_KYBER_LEVEL3},
14000
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
14001
     WOLFSSL_P256_KYBER_LEVEL3},
14002
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
14003
     WOLFSSL_P521_KYBER_LEVEL5},
14004
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
14005
     WOLFSSL_X25519_KYBER_LEVEL1},
14006
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
14007
     WOLFSSL_X448_KYBER_LEVEL3},
14008
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
14009
     WOLFSSL_X25519_KYBER_LEVEL3},
14010
#endif
14011
#endif /* WOLFSSL_MLKEM_KYBER */
14012
#endif /* WOLFSSL_HAVE_MLKEM */
14013
#ifdef WOLFSSL_SM2
14014
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
14015
#endif
14016
#ifdef HAVE_ECC
14017
    /* Alternative curve names */
14018
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
14019
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
14020
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
14021
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
14022
#endif
14023
#ifdef WOLFSSL_SM2
14024
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
14025
#endif
14026
    {0, NULL, 0, 0},
14027
};
14028
14029
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
14030
        byte curves_only)
14031
{
14032
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
14033
    word16 curve;
14034
    word32 disabled;
14035
    char name[MAX_CURVE_NAME_SZ];
14036
    byte groups_len = 0;
14037
#ifdef WOLFSSL_SMALL_STACK
14038
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
14039
    int *groups;
14040
#else
14041
    int groups[WOLFSSL_MAX_GROUP_COUNT];
14042
#endif
14043
    const WOLF_EC_NIST_NAME* nist_name;
14044
14045
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
14046
        DYNAMIC_TYPE_TMP_BUFFER,
14047
    {
14048
        ret=MEMORY_E;
14049
        goto leave;
14050
    });
14051
14052
    for (idx = 1; names[idx-1] != '\0'; idx++) {
14053
        if (names[idx] != ':' && names[idx] != '\0')
14054
            continue;
14055
14056
        len = idx - start;
14057
        if (len > MAX_CURVE_NAME_SZ - 1)
14058
            goto leave;
14059
14060
        XMEMCPY(name, names + start, (size_t)len);
14061
        name[len] = 0;
14062
        curve = WOLFSSL_NAMED_GROUP_INVALID;
14063
14064
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
14065
            if (len == nist_name->name_len &&
14066
                    XSTRNCASECMP(name, nist_name->name, (size_t)len) == 0) {
14067
                curve = nist_name->curve;
14068
                break;
14069
            }
14070
        }
14071
14072
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
14073
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
14074
            int   nret;
14075
            const ecc_set_type *eccSet;
14076
14077
            nret = wc_ecc_get_curve_idx_from_name(name);
14078
            if (nret < 0) {
14079
                WOLFSSL_MSG("Could not find name in set");
14080
                goto leave;
14081
            }
14082
14083
            eccSet = wc_ecc_get_curve_params(nret);
14084
            if (eccSet == NULL) {
14085
                WOLFSSL_MSG("NULL set returned");
14086
                goto leave;
14087
            }
14088
14089
            curve = GetCurveByOID((int)eccSet->oidSum);
14090
        #else
14091
            WOLFSSL_MSG("API not present to search farther using name");
14092
            goto leave;
14093
        #endif
14094
        }
14095
14096
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
14097
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
14098
            WOLFSSL_MSG("curve value is not supported");
14099
            goto leave;
14100
        }
14101
14102
        for (i = 0; i < groups_len; ++i) {
14103
            if (groups[i] == curve) {
14104
                /* silently drop duplicates */
14105
                break;
14106
            }
14107
        }
14108
        if (i >= groups_len) {
14109
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
14110
                WOLFSSL_MSG_EX("setting %d or more supported "
14111
                               "curves is not permitted", groups_len);
14112
                goto leave;
14113
            }
14114
            groups[groups_len++] = (int)curve;
14115
        }
14116
14117
        start = idx + 1;
14118
    }
14119
14120
    /* Disable all curves so that only the ones the user wants are enabled. */
14121
    disabled = 0xFFFFFFFFUL;
14122
    for (i = 0; i < groups_len; ++i) {
14123
        /* Switch the bit to off and therefore is enabled. */
14124
        curve = (word16)groups[i];
14125
        if (curve >= 64) {
14126
            WC_DO_NOTHING;
14127
        }
14128
        else if (curve >= 32) {
14129
            /* 0 is for invalid and 1-14 aren't used otherwise. */
14130
            disabled &= ~(1U << (curve - 32));
14131
        }
14132
        else {
14133
            disabled &= ~(1U << curve);
14134
        }
14135
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
14136
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
14137
        /* using the wolfSSL API to set the groups, this will populate
14138
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
14139
         * The order in (ssl|ctx)->groups will then be respected
14140
         * when TLSX_KEY_SHARE needs to be established */
14141
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
14142
                        != WOLFSSL_SUCCESS)
14143
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
14144
                           != WOLFSSL_SUCCESS)) {
14145
            WOLFSSL_MSG("Unable to set supported curve");
14146
            goto leave;
14147
        }
14148
    #elif !defined(NO_WOLFSSL_CLIENT)
14149
        /* set the supported curve so client TLS extension contains only the
14150
         * desired curves */
14151
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
14152
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
14153
                           != WOLFSSL_SUCCESS)) {
14154
            WOLFSSL_MSG("Unable to set supported curve");
14155
            goto leave;
14156
        }
14157
    #endif
14158
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
14159
    }
14160
14161
    if (ssl != NULL)
14162
        ssl->disabledCurves = disabled;
14163
    else if (ctx != NULL)
14164
        ctx->disabledCurves = disabled;
14165
    ret = WOLFSSL_SUCCESS;
14166
14167
leave:
14168
#ifdef WOLFSSL_SMALL_STACK
14169
    if (groups)
14170
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
14171
#endif
14172
    return ret;
14173
}
14174
14175
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
14176
#endif /* OPENSSL_EXTRA || HAVE_CURL */
14177
14178
14179
#ifdef OPENSSL_EXTRA
14180
/* Sets a callback for when sending and receiving protocol messages.
14181
 * This callback is copied to all WOLFSSL objects created from the ctx.
14182
 *
14183
 * ctx WOLFSSL_CTX structure to set callback in
14184
 * cb  callback to use
14185
 *
14186
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
14187
 */
14188
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
14189
{
14190
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
14191
    if (ctx == NULL) {
14192
        WOLFSSL_MSG("Null ctx passed in");
14193
        return WOLFSSL_FAILURE;
14194
    }
14195
14196
    ctx->protoMsgCb = cb;
14197
    return WOLFSSL_SUCCESS;
14198
}
14199
14200
14201
/* Sets a callback for when sending and receiving protocol messages.
14202
 *
14203
 * ssl WOLFSSL structure to set callback in
14204
 * cb  callback to use
14205
 *
14206
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
14207
 */
14208
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
14209
{
14210
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
14211
14212
    if (ssl == NULL) {
14213
        return WOLFSSL_FAILURE;
14214
    }
14215
14216
    if (cb != NULL) {
14217
        ssl->toInfoOn = 1;
14218
    }
14219
14220
    ssl->protoMsgCb = cb;
14221
    return WOLFSSL_SUCCESS;
14222
}
14223
14224
14225
/* set the user argument to pass to the msg callback when called
14226
 * return WOLFSSL_SUCCESS on success */
14227
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
14228
{
14229
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
14230
    if (ctx == NULL) {
14231
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
14232
        return WOLFSSL_FAILURE;
14233
    }
14234
14235
    ctx->protoMsgCtx = arg;
14236
    return WOLFSSL_SUCCESS;
14237
}
14238
14239
14240
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
14241
{
14242
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
14243
    if (ssl == NULL)
14244
        return WOLFSSL_FAILURE;
14245
14246
    ssl->protoMsgCtx = arg;
14247
    return WOLFSSL_SUCCESS;
14248
}
14249
14250
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
14251
    int line)
14252
{
14253
    void *ret;
14254
    (void)file;
14255
    (void)line;
14256
14257
    if (data == NULL || siz >= INT_MAX)
14258
        return NULL;
14259
14260
    ret = wolfSSL_OPENSSL_malloc(siz);
14261
    if (ret == NULL) {
14262
        return NULL;
14263
    }
14264
    return XMEMCPY(ret, data, siz);
14265
}
14266
14267
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
14268
{
14269
    if (ptr)
14270
        ForceZero(ptr, (word32)len);
14271
}
14272
14273
#endif /* OPENSSL_EXTRA */
14274
14275
#define WOLFSSL_SSL_API_EXT_INCLUDED
14276
#include "src/ssl_api_ext.c"
14277
14278
#if defined(OPENSSL_EXTRA)
14279
14280
#ifndef NO_BIO
14281
#define WOLFSSL_BIO_INCLUDED
14282
#include "src/bio.c"
14283
#endif
14284
14285
#endif /* OPENSSL_EXTRA */
14286
14287
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
14288
14289
word32 nid2oid(int nid, int grp)
14290
{
14291
    /* get OID type */
14292
    switch (grp) {
14293
        /* oidHashType */
14294
        case oidHashType:
14295
            switch (nid) {
14296
            #ifdef WOLFSSL_MD2
14297
                case WC_NID_md2:
14298
                    return MD2h;
14299
            #endif
14300
            #ifndef NO_MD5
14301
                case WC_NID_md5:
14302
                    return MD5h;
14303
            #endif
14304
            #ifndef NO_SHA
14305
                case WC_NID_sha1:
14306
                    return SHAh;
14307
            #endif
14308
                case WC_NID_sha224:
14309
                    return SHA224h;
14310
            #ifndef NO_SHA256
14311
                case WC_NID_sha256:
14312
                    return SHA256h;
14313
            #endif
14314
            #ifdef WOLFSSL_SHA384
14315
                case WC_NID_sha384:
14316
                    return SHA384h;
14317
            #endif
14318
            #ifdef WOLFSSL_SHA512
14319
                case WC_NID_sha512:
14320
                    return SHA512h;
14321
            #endif
14322
            #ifndef WOLFSSL_NOSHA3_224
14323
                case WC_NID_sha3_224:
14324
                    return SHA3_224h;
14325
            #endif
14326
            #ifndef WOLFSSL_NOSHA3_256
14327
                case WC_NID_sha3_256:
14328
                    return SHA3_256h;
14329
            #endif
14330
            #ifndef WOLFSSL_NOSHA3_384
14331
                case WC_NID_sha3_384:
14332
                    return SHA3_384h;
14333
            #endif
14334
            #ifndef WOLFSSL_NOSHA3_512
14335
                case WC_NID_sha3_512:
14336
                    return SHA3_512h;
14337
            #endif
14338
            }
14339
            break;
14340
14341
        /*  oidSigType */
14342
        case oidSigType:
14343
            switch (nid) {
14344
            #ifndef NO_DSA
14345
                case WC_NID_dsaWithSHA1:
14346
                    return CTC_SHAwDSA;
14347
                case WC_NID_dsa_with_SHA256:
14348
                    return CTC_SHA256wDSA;
14349
            #endif /* NO_DSA */
14350
            #ifndef NO_RSA
14351
                case WC_NID_md2WithRSAEncryption:
14352
                    return CTC_MD2wRSA;
14353
                case WC_NID_md5WithRSAEncryption:
14354
                    return CTC_MD5wRSA;
14355
                case WC_NID_sha1WithRSAEncryption:
14356
                    return CTC_SHAwRSA;
14357
                case WC_NID_sha224WithRSAEncryption:
14358
                    return CTC_SHA224wRSA;
14359
                case WC_NID_sha256WithRSAEncryption:
14360
                    return CTC_SHA256wRSA;
14361
                case WC_NID_sha384WithRSAEncryption:
14362
                    return CTC_SHA384wRSA;
14363
                case WC_NID_sha512WithRSAEncryption:
14364
                    return CTC_SHA512wRSA;
14365
                #ifdef WOLFSSL_SHA3
14366
                case WC_NID_RSA_SHA3_224:
14367
                    return CTC_SHA3_224wRSA;
14368
                case WC_NID_RSA_SHA3_256:
14369
                    return CTC_SHA3_256wRSA;
14370
                case WC_NID_RSA_SHA3_384:
14371
                    return CTC_SHA3_384wRSA;
14372
                case WC_NID_RSA_SHA3_512:
14373
                    return CTC_SHA3_512wRSA;
14374
                #endif
14375
            #endif /* NO_RSA */
14376
            #ifdef HAVE_ECC
14377
                case WC_NID_ecdsa_with_SHA1:
14378
                    return CTC_SHAwECDSA;
14379
                case WC_NID_ecdsa_with_SHA224:
14380
                    return CTC_SHA224wECDSA;
14381
                case WC_NID_ecdsa_with_SHA256:
14382
                    return CTC_SHA256wECDSA;
14383
                case WC_NID_ecdsa_with_SHA384:
14384
                    return CTC_SHA384wECDSA;
14385
                case WC_NID_ecdsa_with_SHA512:
14386
                    return CTC_SHA512wECDSA;
14387
                #ifdef WOLFSSL_SHA3
14388
                case WC_NID_ecdsa_with_SHA3_224:
14389
                    return CTC_SHA3_224wECDSA;
14390
                case WC_NID_ecdsa_with_SHA3_256:
14391
                    return CTC_SHA3_256wECDSA;
14392
                case WC_NID_ecdsa_with_SHA3_384:
14393
                    return CTC_SHA3_384wECDSA;
14394
                case WC_NID_ecdsa_with_SHA3_512:
14395
                    return CTC_SHA3_512wECDSA;
14396
                #endif
14397
            #endif /* HAVE_ECC */
14398
            #ifdef HAVE_ED25519
14399
                case WC_NID_ED25519:
14400
                    return CTC_ED25519;
14401
            #endif /* HAVE_ED25519 */
14402
            #ifdef HAVE_ED448
14403
                case WC_NID_ED448:
14404
                    return CTC_ED448;
14405
            #endif /* HAVE_ED448 */
14406
            }
14407
            break;
14408
14409
        /* oidKeyType */
14410
        case oidKeyType:
14411
            switch (nid) {
14412
            #ifndef NO_DSA
14413
                case WC_NID_dsa:
14414
                    return DSAk;
14415
            #endif /* NO_DSA */
14416
            #ifndef NO_RSA
14417
                case WC_NID_rsaEncryption:
14418
                    return RSAk;
14419
            #endif /* NO_RSA */
14420
            #ifdef HAVE_ECC
14421
                case WC_NID_X9_62_id_ecPublicKey:
14422
                    return ECDSAk;
14423
            #endif /* HAVE_ECC */
14424
            #ifdef HAVE_ED25519
14425
                case WC_NID_ED25519:
14426
                    return ED25519k;
14427
            #endif /* HAVE_ED25519 */
14428
            #ifdef HAVE_ED448
14429
                case WC_NID_ED448:
14430
                    return ED448k;
14431
            #endif /* HAVE_ED448 */
14432
            }
14433
            break;
14434
14435
14436
    #ifdef HAVE_ECC
14437
        case oidCurveType:
14438
            switch (nid) {
14439
            case WC_NID_X9_62_prime192v1:
14440
                return ECC_SECP192R1_OID;
14441
            case WC_NID_X9_62_prime192v2:
14442
                return ECC_PRIME192V2_OID;
14443
            case WC_NID_X9_62_prime192v3:
14444
                return ECC_PRIME192V3_OID;
14445
            case WC_NID_X9_62_prime239v1:
14446
                return ECC_PRIME239V1_OID;
14447
            case WC_NID_X9_62_prime239v2:
14448
                return ECC_PRIME239V2_OID;
14449
            case WC_NID_X9_62_prime239v3:
14450
                return ECC_PRIME239V3_OID;
14451
            case WC_NID_X9_62_prime256v1:
14452
                return ECC_SECP256R1_OID;
14453
            case WC_NID_secp112r1:
14454
                return ECC_SECP112R1_OID;
14455
            case WC_NID_secp112r2:
14456
                return ECC_SECP112R2_OID;
14457
            case WC_NID_secp128r1:
14458
                return ECC_SECP128R1_OID;
14459
            case WC_NID_secp128r2:
14460
                return ECC_SECP128R2_OID;
14461
            case WC_NID_secp160r1:
14462
                return ECC_SECP160R1_OID;
14463
            case WC_NID_secp160r2:
14464
                return ECC_SECP160R2_OID;
14465
            case WC_NID_secp224r1:
14466
                return ECC_SECP224R1_OID;
14467
            case WC_NID_secp384r1:
14468
                return ECC_SECP384R1_OID;
14469
            case WC_NID_secp521r1:
14470
                return ECC_SECP521R1_OID;
14471
            case WC_NID_secp160k1:
14472
                return ECC_SECP160K1_OID;
14473
            case WC_NID_secp192k1:
14474
                return ECC_SECP192K1_OID;
14475
            case WC_NID_secp224k1:
14476
                return ECC_SECP224K1_OID;
14477
            case WC_NID_secp256k1:
14478
                return ECC_SECP256K1_OID;
14479
            case WC_NID_brainpoolP160r1:
14480
                return ECC_BRAINPOOLP160R1_OID;
14481
            case WC_NID_brainpoolP192r1:
14482
                return ECC_BRAINPOOLP192R1_OID;
14483
            case WC_NID_brainpoolP224r1:
14484
                return ECC_BRAINPOOLP224R1_OID;
14485
            case WC_NID_brainpoolP256r1:
14486
                return ECC_BRAINPOOLP256R1_OID;
14487
            case WC_NID_brainpoolP320r1:
14488
                return ECC_BRAINPOOLP320R1_OID;
14489
            case WC_NID_brainpoolP384r1:
14490
                return ECC_BRAINPOOLP384R1_OID;
14491
            case WC_NID_brainpoolP512r1:
14492
                return ECC_BRAINPOOLP512R1_OID;
14493
            }
14494
            break;
14495
    #endif /* HAVE_ECC */
14496
14497
        /* oidBlkType */
14498
        case oidBlkType:
14499
            switch (nid) {
14500
            #ifdef WOLFSSL_AES_128
14501
                case AES128CBCb:
14502
                    return AES128CBCb;
14503
            #endif
14504
            #ifdef WOLFSSL_AES_192
14505
                case AES192CBCb:
14506
                    return AES192CBCb;
14507
            #endif
14508
            #ifdef WOLFSSL_AES_256
14509
                case AES256CBCb:
14510
                    return AES256CBCb;
14511
            #endif
14512
            #ifndef NO_DES3
14513
                case WC_NID_des:
14514
                    return DESb;
14515
                case WC_NID_des3:
14516
                    return DES3b;
14517
            #endif
14518
            }
14519
            break;
14520
14521
    #ifdef HAVE_OCSP
14522
        case oidOcspType:
14523
            switch (nid) {
14524
                case WC_NID_id_pkix_OCSP_basic:
14525
                    return OCSP_BASIC_OID;
14526
                case OCSP_NONCE_OID:
14527
                    return OCSP_NONCE_OID;
14528
            }
14529
            break;
14530
    #endif /* HAVE_OCSP */
14531
14532
        /* oidCertExtType */
14533
        case oidCertExtType:
14534
            switch (nid) {
14535
                case WC_NID_basic_constraints:
14536
                    return BASIC_CA_OID;
14537
                case WC_NID_subject_alt_name:
14538
                    return ALT_NAMES_OID;
14539
                case WC_NID_crl_distribution_points:
14540
                    return CRL_DIST_OID;
14541
                case WC_NID_info_access:
14542
                    return AUTH_INFO_OID;
14543
                case WC_NID_authority_key_identifier:
14544
                    return AUTH_KEY_OID;
14545
                case WC_NID_subject_key_identifier:
14546
                    return SUBJ_KEY_OID;
14547
                case WC_NID_inhibit_any_policy:
14548
                    return INHIBIT_ANY_OID;
14549
                case WC_NID_key_usage:
14550
                    return KEY_USAGE_OID;
14551
                case WC_NID_name_constraints:
14552
                    return NAME_CONS_OID;
14553
                case WC_NID_certificate_policies:
14554
                    return CERT_POLICY_OID;
14555
                case WC_NID_ext_key_usage:
14556
                    return EXT_KEY_USAGE_OID;
14557
            }
14558
            break;
14559
14560
        /* oidCertAuthInfoType */
14561
        case oidCertAuthInfoType:
14562
            switch (nid) {
14563
                case WC_NID_ad_OCSP:
14564
                    return AIA_OCSP_OID;
14565
                case WC_NID_ad_ca_issuers:
14566
                    return AIA_CA_ISSUER_OID;
14567
            }
14568
            break;
14569
14570
        /* oidCertPolicyType */
14571
        case oidCertPolicyType:
14572
            switch (nid) {
14573
                case WC_NID_any_policy:
14574
                    return CP_ANY_OID;
14575
            }
14576
            break;
14577
14578
        /* oidCertAltNameType */
14579
        case oidCertAltNameType:
14580
            switch (nid) {
14581
                case WC_NID_hw_name_oid:
14582
                    return HW_NAME_OID;
14583
            }
14584
            break;
14585
14586
        /* oidCertKeyUseType */
14587
        case oidCertKeyUseType:
14588
            switch (nid) {
14589
                case WC_NID_anyExtendedKeyUsage:
14590
                    return EKU_ANY_OID;
14591
                case EKU_SERVER_AUTH_OID:
14592
                    return EKU_SERVER_AUTH_OID;
14593
                case EKU_CLIENT_AUTH_OID:
14594
                    return EKU_CLIENT_AUTH_OID;
14595
                case EKU_OCSP_SIGN_OID:
14596
                    return EKU_OCSP_SIGN_OID;
14597
            }
14598
            break;
14599
14600
        /* oidKdfType */
14601
        case oidKdfType:
14602
            switch (nid) {
14603
                case PBKDF2_OID:
14604
                    return PBKDF2_OID;
14605
            }
14606
            break;
14607
14608
        /* oidPBEType */
14609
        case oidPBEType:
14610
            switch (nid) {
14611
                case PBE_SHA1_RC4_128:
14612
                    return PBE_SHA1_RC4_128;
14613
                case PBE_SHA1_DES:
14614
                    return PBE_SHA1_DES;
14615
                case PBE_SHA1_DES3:
14616
                    return PBE_SHA1_DES3;
14617
            }
14618
            break;
14619
14620
        /* oidKeyWrapType */
14621
        case oidKeyWrapType:
14622
            switch (nid) {
14623
            #ifdef WOLFSSL_AES_128
14624
                case AES128_WRAP:
14625
                    return AES128_WRAP;
14626
            #endif
14627
            #ifdef WOLFSSL_AES_192
14628
                case AES192_WRAP:
14629
                    return AES192_WRAP;
14630
            #endif
14631
            #ifdef WOLFSSL_AES_256
14632
                case AES256_WRAP:
14633
                    return AES256_WRAP;
14634
            #endif
14635
            }
14636
            break;
14637
14638
        /* oidCmsKeyAgreeType */
14639
        case oidCmsKeyAgreeType:
14640
            switch (nid) {
14641
                #ifndef NO_SHA
14642
                case dhSinglePass_stdDH_sha1kdf_scheme:
14643
                    return dhSinglePass_stdDH_sha1kdf_scheme;
14644
                #endif
14645
                #ifdef WOLFSSL_SHA224
14646
                case dhSinglePass_stdDH_sha224kdf_scheme:
14647
                    return dhSinglePass_stdDH_sha224kdf_scheme;
14648
                #endif
14649
                #ifndef NO_SHA256
14650
                case dhSinglePass_stdDH_sha256kdf_scheme:
14651
                    return dhSinglePass_stdDH_sha256kdf_scheme;
14652
                #endif
14653
                #ifdef WOLFSSL_SHA384
14654
                case dhSinglePass_stdDH_sha384kdf_scheme:
14655
                    return dhSinglePass_stdDH_sha384kdf_scheme;
14656
                #endif
14657
                #ifdef WOLFSSL_SHA512
14658
                case dhSinglePass_stdDH_sha512kdf_scheme:
14659
                    return dhSinglePass_stdDH_sha512kdf_scheme;
14660
                #endif
14661
            }
14662
            break;
14663
14664
        /* oidCmsKeyAgreeType */
14665
    #ifdef WOLFSSL_CERT_REQ
14666
        case oidCsrAttrType:
14667
            switch (nid) {
14668
                case WC_NID_pkcs9_contentType:
14669
                    return PKCS9_CONTENT_TYPE_OID;
14670
                case WC_NID_pkcs9_challengePassword:
14671
                    return CHALLENGE_PASSWORD_OID;
14672
                case WC_NID_serialNumber:
14673
                    return SERIAL_NUMBER_OID;
14674
                case WC_NID_userId:
14675
                    return USER_ID_OID;
14676
                case WC_NID_surname:
14677
                    return SURNAME_OID;
14678
            }
14679
            break;
14680
    #endif
14681
14682
        default:
14683
            WOLFSSL_MSG("NID not in table");
14684
            /* MSVC warns without the cast */
14685
            return (word32)-1;
14686
    }
14687
14688
    /* MSVC warns without the cast */
14689
    return (word32)-1;
14690
}
14691
14692
int oid2nid(word32 oid, int grp)
14693
{
14694
    size_t i;
14695
    /* get OID type */
14696
    switch (grp) {
14697
        /* oidHashType */
14698
        case oidHashType:
14699
            switch (oid) {
14700
            #ifdef WOLFSSL_MD2
14701
                case MD2h:
14702
                    return WC_NID_md2;
14703
            #endif
14704
            #ifndef NO_MD5
14705
                case MD5h:
14706
                    return WC_NID_md5;
14707
            #endif
14708
            #ifndef NO_SHA
14709
                case SHAh:
14710
                    return WC_NID_sha1;
14711
            #endif
14712
                case SHA224h:
14713
                    return WC_NID_sha224;
14714
            #ifndef NO_SHA256
14715
                case SHA256h:
14716
                    return WC_NID_sha256;
14717
            #endif
14718
            #ifdef WOLFSSL_SHA384
14719
                case SHA384h:
14720
                    return WC_NID_sha384;
14721
            #endif
14722
            #ifdef WOLFSSL_SHA512
14723
                case SHA512h:
14724
                    return WC_NID_sha512;
14725
            #endif
14726
            }
14727
            break;
14728
14729
        /*  oidSigType */
14730
        case oidSigType:
14731
            switch (oid) {
14732
            #ifndef NO_DSA
14733
                case CTC_SHAwDSA:
14734
                    return WC_NID_dsaWithSHA1;
14735
                case CTC_SHA256wDSA:
14736
                    return WC_NID_dsa_with_SHA256;
14737
            #endif /* NO_DSA */
14738
            #ifndef NO_RSA
14739
                case CTC_MD2wRSA:
14740
                    return WC_NID_md2WithRSAEncryption;
14741
                case CTC_MD5wRSA:
14742
                    return WC_NID_md5WithRSAEncryption;
14743
                case CTC_SHAwRSA:
14744
                    return WC_NID_sha1WithRSAEncryption;
14745
                case CTC_SHA224wRSA:
14746
                    return WC_NID_sha224WithRSAEncryption;
14747
                case CTC_SHA256wRSA:
14748
                    return WC_NID_sha256WithRSAEncryption;
14749
                case CTC_SHA384wRSA:
14750
                    return WC_NID_sha384WithRSAEncryption;
14751
                case CTC_SHA512wRSA:
14752
                    return WC_NID_sha512WithRSAEncryption;
14753
                #ifdef WOLFSSL_SHA3
14754
                case CTC_SHA3_224wRSA:
14755
                    return WC_NID_RSA_SHA3_224;
14756
                case CTC_SHA3_256wRSA:
14757
                    return WC_NID_RSA_SHA3_256;
14758
                case CTC_SHA3_384wRSA:
14759
                    return WC_NID_RSA_SHA3_384;
14760
                case CTC_SHA3_512wRSA:
14761
                    return WC_NID_RSA_SHA3_512;
14762
                #endif
14763
                #ifdef WC_RSA_PSS
14764
                case CTC_RSASSAPSS:
14765
                    return WC_NID_rsassaPss;
14766
                #endif
14767
            #endif /* NO_RSA */
14768
            #ifdef HAVE_ECC
14769
                case CTC_SHAwECDSA:
14770
                    return WC_NID_ecdsa_with_SHA1;
14771
                case CTC_SHA224wECDSA:
14772
                    return WC_NID_ecdsa_with_SHA224;
14773
                case CTC_SHA256wECDSA:
14774
                    return WC_NID_ecdsa_with_SHA256;
14775
                case CTC_SHA384wECDSA:
14776
                    return WC_NID_ecdsa_with_SHA384;
14777
                case CTC_SHA512wECDSA:
14778
                    return WC_NID_ecdsa_with_SHA512;
14779
                #ifdef WOLFSSL_SHA3
14780
                case CTC_SHA3_224wECDSA:
14781
                    return WC_NID_ecdsa_with_SHA3_224;
14782
                case CTC_SHA3_256wECDSA:
14783
                    return WC_NID_ecdsa_with_SHA3_256;
14784
                case CTC_SHA3_384wECDSA:
14785
                    return WC_NID_ecdsa_with_SHA3_384;
14786
                case CTC_SHA3_512wECDSA:
14787
                    return WC_NID_ecdsa_with_SHA3_512;
14788
                #endif
14789
            #endif /* HAVE_ECC */
14790
            #ifdef HAVE_ED25519
14791
                case CTC_ED25519:
14792
                    return WC_NID_ED25519;
14793
            #endif /* HAVE_ED25519 */
14794
            #ifdef HAVE_ED448
14795
                case CTC_ED448:
14796
                    return WC_NID_ED448;
14797
            #endif /* HAVE_ED448 */
14798
            }
14799
            break;
14800
14801
        /* oidKeyType */
14802
        case oidKeyType:
14803
            switch (oid) {
14804
            #ifndef NO_DSA
14805
                case DSAk:
14806
                    return WC_NID_dsa;
14807
            #endif /* NO_DSA */
14808
            #ifndef NO_RSA
14809
                case RSAk:
14810
                    return WC_NID_rsaEncryption;
14811
                #ifdef WC_RSA_PSS
14812
                case RSAPSSk:
14813
                    return WC_NID_rsassaPss;
14814
                #endif
14815
            #endif /* NO_RSA */
14816
            #ifdef HAVE_ECC
14817
                case ECDSAk:
14818
                    return WC_NID_X9_62_id_ecPublicKey;
14819
            #endif /* HAVE_ECC */
14820
            #ifdef HAVE_ED25519
14821
                case ED25519k:
14822
                    return WC_NID_ED25519;
14823
            #endif /* HAVE_ED25519 */
14824
            #ifdef HAVE_ED448
14825
                case ED448k:
14826
                    return WC_NID_ED448;
14827
            #endif /* HAVE_ED448 */
14828
            }
14829
            break;
14830
14831
14832
    #ifdef HAVE_ECC
14833
        case oidCurveType:
14834
            switch (oid) {
14835
            case ECC_SECP192R1_OID:
14836
                return WC_NID_X9_62_prime192v1;
14837
            case ECC_PRIME192V2_OID:
14838
                return WC_NID_X9_62_prime192v2;
14839
            case ECC_PRIME192V3_OID:
14840
                return WC_NID_X9_62_prime192v3;
14841
            case ECC_PRIME239V1_OID:
14842
                return WC_NID_X9_62_prime239v1;
14843
            case ECC_PRIME239V2_OID:
14844
                return WC_NID_X9_62_prime239v2;
14845
            case ECC_PRIME239V3_OID:
14846
                return WC_NID_X9_62_prime239v3;
14847
            case ECC_SECP256R1_OID:
14848
                return WC_NID_X9_62_prime256v1;
14849
            case ECC_SECP112R1_OID:
14850
                return WC_NID_secp112r1;
14851
            case ECC_SECP112R2_OID:
14852
                return WC_NID_secp112r2;
14853
            case ECC_SECP128R1_OID:
14854
                return WC_NID_secp128r1;
14855
            case ECC_SECP128R2_OID:
14856
                return WC_NID_secp128r2;
14857
            case ECC_SECP160R1_OID:
14858
                return WC_NID_secp160r1;
14859
            case ECC_SECP160R2_OID:
14860
                return WC_NID_secp160r2;
14861
            case ECC_SECP224R1_OID:
14862
                return WC_NID_secp224r1;
14863
            case ECC_SECP384R1_OID:
14864
                return WC_NID_secp384r1;
14865
            case ECC_SECP521R1_OID:
14866
                return WC_NID_secp521r1;
14867
            case ECC_SECP160K1_OID:
14868
                return WC_NID_secp160k1;
14869
            case ECC_SECP192K1_OID:
14870
                return WC_NID_secp192k1;
14871
            case ECC_SECP224K1_OID:
14872
                return WC_NID_secp224k1;
14873
            case ECC_SECP256K1_OID:
14874
                return WC_NID_secp256k1;
14875
            case ECC_BRAINPOOLP160R1_OID:
14876
                return WC_NID_brainpoolP160r1;
14877
            case ECC_BRAINPOOLP192R1_OID:
14878
                return WC_NID_brainpoolP192r1;
14879
            case ECC_BRAINPOOLP224R1_OID:
14880
                return WC_NID_brainpoolP224r1;
14881
            case ECC_BRAINPOOLP256R1_OID:
14882
                return WC_NID_brainpoolP256r1;
14883
            case ECC_BRAINPOOLP320R1_OID:
14884
                return WC_NID_brainpoolP320r1;
14885
            case ECC_BRAINPOOLP384R1_OID:
14886
                return WC_NID_brainpoolP384r1;
14887
            case ECC_BRAINPOOLP512R1_OID:
14888
                return WC_NID_brainpoolP512r1;
14889
            }
14890
            break;
14891
    #endif /* HAVE_ECC */
14892
14893
        /* oidBlkType */
14894
        case oidBlkType:
14895
            switch (oid) {
14896
            #ifdef WOLFSSL_AES_128
14897
                case AES128CBCb:
14898
                    return AES128CBCb;
14899
            #endif
14900
            #ifdef WOLFSSL_AES_192
14901
                case AES192CBCb:
14902
                    return AES192CBCb;
14903
            #endif
14904
            #ifdef WOLFSSL_AES_256
14905
                case AES256CBCb:
14906
                    return AES256CBCb;
14907
            #endif
14908
            #ifndef NO_DES3
14909
                case DESb:
14910
                    return WC_NID_des;
14911
                case DES3b:
14912
                    return WC_NID_des3;
14913
            #endif
14914
            }
14915
            break;
14916
14917
    #ifdef HAVE_OCSP
14918
        case oidOcspType:
14919
            switch (oid) {
14920
                case OCSP_BASIC_OID:
14921
                    return WC_NID_id_pkix_OCSP_basic;
14922
                case OCSP_NONCE_OID:
14923
                    return OCSP_NONCE_OID;
14924
            }
14925
            break;
14926
    #endif /* HAVE_OCSP */
14927
14928
        /* oidCertExtType */
14929
        case oidCertExtType:
14930
            switch (oid) {
14931
                case BASIC_CA_OID:
14932
                    return WC_NID_basic_constraints;
14933
                case ALT_NAMES_OID:
14934
                    return WC_NID_subject_alt_name;
14935
                case CRL_DIST_OID:
14936
                    return WC_NID_crl_distribution_points;
14937
                case AUTH_INFO_OID:
14938
                    return WC_NID_info_access;
14939
                case AUTH_KEY_OID:
14940
                    return WC_NID_authority_key_identifier;
14941
                case SUBJ_KEY_OID:
14942
                    return WC_NID_subject_key_identifier;
14943
                case INHIBIT_ANY_OID:
14944
                    return WC_NID_inhibit_any_policy;
14945
                case KEY_USAGE_OID:
14946
                    return WC_NID_key_usage;
14947
                case NAME_CONS_OID:
14948
                    return WC_NID_name_constraints;
14949
                case CERT_POLICY_OID:
14950
                    return WC_NID_certificate_policies;
14951
                case EXT_KEY_USAGE_OID:
14952
                    return WC_NID_ext_key_usage;
14953
            }
14954
            break;
14955
14956
        /* oidCertAuthInfoType */
14957
        case oidCertAuthInfoType:
14958
            switch (oid) {
14959
                case AIA_OCSP_OID:
14960
                    return WC_NID_ad_OCSP;
14961
                case AIA_CA_ISSUER_OID:
14962
                    return WC_NID_ad_ca_issuers;
14963
            }
14964
            break;
14965
14966
        /* oidCertPolicyType */
14967
        case oidCertPolicyType:
14968
            switch (oid) {
14969
                case CP_ANY_OID:
14970
                    return WC_NID_any_policy;
14971
            }
14972
            break;
14973
14974
        /* oidCertAltNameType */
14975
        case oidCertAltNameType:
14976
            switch (oid) {
14977
                case HW_NAME_OID:
14978
                    return WC_NID_hw_name_oid;
14979
            }
14980
            break;
14981
14982
        /* oidCertKeyUseType */
14983
        case oidCertKeyUseType:
14984
            switch (oid) {
14985
                case EKU_ANY_OID:
14986
                    return WC_NID_anyExtendedKeyUsage;
14987
                case EKU_SERVER_AUTH_OID:
14988
                    return EKU_SERVER_AUTH_OID;
14989
                case EKU_CLIENT_AUTH_OID:
14990
                    return EKU_CLIENT_AUTH_OID;
14991
                case EKU_OCSP_SIGN_OID:
14992
                    return EKU_OCSP_SIGN_OID;
14993
            }
14994
            break;
14995
14996
        /* oidKdfType */
14997
        case oidKdfType:
14998
            switch (oid) {
14999
                case PBKDF2_OID:
15000
                    return PBKDF2_OID;
15001
            }
15002
            break;
15003
15004
        /* oidPBEType */
15005
        case oidPBEType:
15006
            switch (oid) {
15007
                case PBE_SHA1_RC4_128:
15008
                    return PBE_SHA1_RC4_128;
15009
                case PBE_SHA1_DES:
15010
                    return PBE_SHA1_DES;
15011
                case PBE_SHA1_DES3:
15012
                    return PBE_SHA1_DES3;
15013
            }
15014
            break;
15015
15016
        /* oidKeyWrapType */
15017
        case oidKeyWrapType:
15018
            switch (oid) {
15019
            #ifdef WOLFSSL_AES_128
15020
                case AES128_WRAP:
15021
                    return AES128_WRAP;
15022
            #endif
15023
            #ifdef WOLFSSL_AES_192
15024
                case AES192_WRAP:
15025
                    return AES192_WRAP;
15026
            #endif
15027
            #ifdef WOLFSSL_AES_256
15028
                case AES256_WRAP:
15029
                    return AES256_WRAP;
15030
            #endif
15031
            }
15032
            break;
15033
15034
        /* oidCmsKeyAgreeType */
15035
        case oidCmsKeyAgreeType:
15036
            switch (oid) {
15037
                #ifndef NO_SHA
15038
                case dhSinglePass_stdDH_sha1kdf_scheme:
15039
                    return dhSinglePass_stdDH_sha1kdf_scheme;
15040
                #endif
15041
                #ifdef WOLFSSL_SHA224
15042
                case dhSinglePass_stdDH_sha224kdf_scheme:
15043
                    return dhSinglePass_stdDH_sha224kdf_scheme;
15044
                #endif
15045
                #ifndef NO_SHA256
15046
                case dhSinglePass_stdDH_sha256kdf_scheme:
15047
                    return dhSinglePass_stdDH_sha256kdf_scheme;
15048
                #endif
15049
                #ifdef WOLFSSL_SHA384
15050
                case dhSinglePass_stdDH_sha384kdf_scheme:
15051
                    return dhSinglePass_stdDH_sha384kdf_scheme;
15052
                #endif
15053
                #ifdef WOLFSSL_SHA512
15054
                case dhSinglePass_stdDH_sha512kdf_scheme:
15055
                    return dhSinglePass_stdDH_sha512kdf_scheme;
15056
                #endif
15057
            }
15058
            break;
15059
15060
#ifdef WOLFSSL_CERT_REQ
15061
        case oidCsrAttrType:
15062
            switch (oid) {
15063
                case PKCS9_CONTENT_TYPE_OID:
15064
                    return WC_NID_pkcs9_contentType;
15065
                case CHALLENGE_PASSWORD_OID:
15066
                    return WC_NID_pkcs9_challengePassword;
15067
                case SERIAL_NUMBER_OID:
15068
                    return WC_NID_serialNumber;
15069
                case USER_ID_OID:
15070
                    return WC_NID_userId;
15071
            }
15072
            break;
15073
#endif
15074
15075
        default:
15076
            WOLFSSL_MSG("OID not in table");
15077
    }
15078
    /* If not found in above switch then try the table */
15079
    for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
15080
        if (wolfssl_object_info[i].id == (int)oid) {
15081
            return wolfssl_object_info[i].nid;
15082
        }
15083
    }
15084
15085
    return WOLFSSL_FATAL_ERROR;
15086
}
15087
15088
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
15089
15090
#if defined(OPENSSL_EXTRA)
15091
15092
/* frees all nodes in the current threads error queue
15093
 *
15094
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
15095
 *     current threads queue will be free'd.
15096
 */
15097
void wolfSSL_ERR_remove_state(unsigned long id)
15098
{
15099
    WOLFSSL_ENTER("wolfSSL_ERR_remove_state");
15100
    (void)id;
15101
    if (wc_ERR_remove_state() != 0) {
15102
        WOLFSSL_MSG("Error with removing the state");
15103
    }
15104
}
15105
15106
#endif /* OPENSSL_EXTRA */
15107
15108
15109
#if defined(OPENSSL_EXTRA)
15110
/* wolfSSL_THREADID_current is provided as a compat API with
15111
 * CRYPTO_THREADID_current to register current thread id into given id object.
15112
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
15113
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
15114
 * like as existing wolfSSL_THREADID_set_numeric.
15115
 */
15116
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
15117
{
15118
    (void)id;
15119
    return;
15120
}
15121
/* wolfSSL_THREADID_hash is provided as a compatible API with
15122
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
15123
 * specified thread id. However, CRYPTO_THREADID_hash API has been
15124
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
15125
 * This API only works as a stub to returns 0. This behavior is
15126
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
15127
 */
15128
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
15129
{
15130
    (void)id;
15131
    return 0UL;
15132
}
15133
15134
/**
15135
 * Set security level (wolfSSL doesn't support setting the security level).
15136
 *
15137
 * The security level can only be set through a system wide crypto-policy
15138
 * with wolfSSL_crypto_policy_enable().
15139
 *
15140
 * @param ctx  a pointer to WOLFSSL_CTX structure
15141
 * @param level security level
15142
 */
15143
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
15144
{
15145
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
15146
    (void)ctx;
15147
    (void)level;
15148
}
15149
15150
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
15151
{
15152
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
15153
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
15154
    if (ctx == NULL) {
15155
        return BAD_FUNC_ARG;
15156
    }
15157
15158
    return ctx->secLevel;
15159
    #else
15160
    (void)ctx;
15161
    return 0;
15162
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
15163
}
15164
15165
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
15166
/*
15167
 * This API accepts a user callback which puts key-log records into
15168
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
15169
 * each SSL object on its creation timing.
15170
 */
15171
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
15172
    wolfSSL_CTX_keylog_cb_func cb)
15173
{
15174
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
15175
    /* stores the callback into WOLFSSL_CTX */
15176
    if (ctx != NULL) {
15177
        ctx->keyLogCb = cb;
15178
    }
15179
}
15180
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
15181
    const WOLFSSL_CTX* ctx)
15182
{
15183
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
15184
    if (ctx != NULL)
15185
        return ctx->keyLogCb;
15186
    return NULL;
15187
}
15188
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
15189
15190
#endif /* OPENSSL_EXTRA */
15191
15192
#ifdef WOLFSSL_THREADED_CRYPT
15193
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
15194
{
15195
    ThreadCrypt* encrypt;
15196
15197
    if (ssl == NULL) {
15198
        return 0;
15199
    }
15200
15201
    encrypt = &ssl->buffers.encrypt[idx];
15202
    return (encrypt->avail == 0) && (encrypt->done == 0);
15203
}
15204
15205
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
15206
{
15207
    ThreadCrypt* encrypt;
15208
15209
    if (ssl == NULL) {
15210
        return 1;
15211
    }
15212
15213
    encrypt = &ssl->buffers.encrypt[idx];
15214
    return encrypt->stop;
15215
}
15216
15217
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
15218
{
15219
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
15220
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
15221
15222
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
15223
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
15224
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
15225
        word32 encSz = encrypt->buffer.length - encrypt->offset;
15226
15227
        ret =
15228
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
15229
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
15230
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
15231
              wc_AesGcmEncrypt_ex
15232
#else
15233
              wc_AesGcmEncrypt
15234
#endif
15235
              (encrypt->encrypt.aes,
15236
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
15237
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
15238
               encrypt->nonce, AESGCM_NONCE_SZ,
15239
               out + encSz - ssl->specs.aead_mac_size,
15240
               ssl->specs.aead_mac_size,
15241
               encrypt->additional, AEAD_AUTH_DATA_SZ);
15242
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
15243
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
15244
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
15245
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
15246
#endif
15247
        encrypt->done = 1;
15248
    }
15249
15250
    return ret;
15251
}
15252
15253
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
15254
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
15255
{
15256
    int ret = 0;
15257
15258
    if (ssl == NULL) {
15259
        ret = BAD_FUNC_ARG;
15260
    }
15261
    else {
15262
        ssl->buffers.encrypt[idx].signal = signal;
15263
        ssl->buffers.encrypt[idx].signalCtx = ctx;
15264
    }
15265
15266
    return ret;
15267
}
15268
#endif
15269
15270
15271
#ifndef NO_CERT
15272
#define WOLFSSL_X509_INCLUDED
15273
#include "src/x509.c"
15274
#endif
15275
15276
/*******************************************************************************
15277
 * START OF standard C library wrapping APIs
15278
 ******************************************************************************/
15279
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
15280
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
15281
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
15282
     defined(WOLFSSL_OPENSSH)))
15283
#ifndef NO_WOLFSSL_STUB
15284
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
15285
                                void *(*r) (void *, size_t, const char *,
15286
                                            int), void (*f) (void *))
15287
{
15288
    (void) m;
15289
    (void) r;
15290
    (void) f;
15291
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
15292
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
15293
15294
    return WOLFSSL_FAILURE;
15295
}
15296
#endif
15297
#endif
15298
15299
#if defined(OPENSSL_EXTRA)
15300
15301
/**
15302
 * free allocated memory resource
15303
 * @param str  a pointer to resource to be freed
15304
 * @param file dummy argument
15305
 * @param line dummy argument
15306
 */
15307
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
15308
{
15309
    (void)file;
15310
    (void)line;
15311
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
15312
}
15313
/**
15314
 * allocate memory with size of num
15315
 * @param num  size of memory allocation to be malloced
15316
 * @param file dummy argument
15317
 * @param line dummy argument
15318
 * @return a pointer to allocated memory on succssesful, otherwise NULL
15319
 */
15320
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
15321
{
15322
    (void)file;
15323
    (void)line;
15324
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
15325
}
15326
15327
#endif
15328
15329
/*******************************************************************************
15330
 * END OF standard C library wrapping APIs
15331
 ******************************************************************************/
15332
15333
/*******************************************************************************
15334
 * START OF EX_DATA APIs
15335
 ******************************************************************************/
15336
#ifdef HAVE_EX_DATA
15337
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
15338
{
15339
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
15340
}
15341
15342
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
15343
{
15344
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
15345
#ifdef MAX_EX_DATA
15346
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15347
        return ex_data->ex_data[idx];
15348
    }
15349
#else
15350
    (void)ex_data;
15351
    (void)idx;
15352
#endif
15353
    return NULL;
15354
}
15355
15356
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
15357
    void *data)
15358
{
15359
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
15360
#ifdef MAX_EX_DATA
15361
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15362
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15363
        if (ex_data->ex_data_cleanup_routines[idx]) {
15364
            /* call cleanup then remove cleanup callback,
15365
             * since different value is being set */
15366
            if (ex_data->ex_data[idx])
15367
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
15368
            ex_data->ex_data_cleanup_routines[idx] = NULL;
15369
        }
15370
#endif
15371
        ex_data->ex_data[idx] = data;
15372
        return WOLFSSL_SUCCESS;
15373
    }
15374
#else
15375
    (void)ex_data;
15376
    (void)idx;
15377
    (void)data;
15378
#endif
15379
    return WOLFSSL_FAILURE;
15380
}
15381
15382
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15383
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
15384
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
15385
    int idx,
15386
    void *data,
15387
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
15388
{
15389
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
15390
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
15391
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
15392
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
15393
        ex_data->ex_data[idx] = data;
15394
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
15395
        return WOLFSSL_SUCCESS;
15396
    }
15397
    return WOLFSSL_FAILURE;
15398
}
15399
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
15400
#endif /* HAVE_EX_DATA */
15401
15402
#ifdef HAVE_EX_DATA_CRYPTO
15403
/**
15404
 * Issues unique index for the class specified by class_index.
15405
 * Other parameter except class_index are ignored.
15406
 * Currently, following class_index are accepted:
15407
 *  - WOLF_CRYPTO_EX_INDEX_SSL
15408
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
15409
 *  - WOLF_CRYPTO_EX_INDEX_X509
15410
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
15411
 * @param argp  parameters to be saved
15412
 * @param argl  parameters to be saved
15413
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
15414
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
15415
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
15416
 * @return index value grater or equal to zero on success, -1 on failure.
15417
 */
15418
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
15419
                                           WOLFSSL_CRYPTO_EX_new* new_func,
15420
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
15421
                                           WOLFSSL_CRYPTO_EX_free* free_func)
15422
{
15423
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
15424
15425
    return wolfssl_local_get_ex_new_index(class_index, argl, argp, new_func,
15426
            dup_func, free_func);
15427
}
15428
#endif /* HAVE_EX_DATA_CRYPTO */
15429
15430
/*******************************************************************************
15431
 * END OF EX_DATA APIs
15432
 ******************************************************************************/
15433
15434
/*******************************************************************************
15435
 * START OF BUF_MEM API
15436
 ******************************************************************************/
15437
15438
#if defined(OPENSSL_EXTRA)
15439
15440
/* Begin functions for openssl/buffer.h */
15441
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
15442
{
15443
    WOLFSSL_BUF_MEM* buf;
15444
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
15445
                                                        DYNAMIC_TYPE_OPENSSL);
15446
    if (buf) {
15447
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
15448
    }
15449
    return buf;
15450
}
15451
15452
/* non-compat API returns length of buffer on success */
15453
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
15454
        char zeroFill)
15455
{
15456
    size_t mx;
15457
    char* tmp;
15458
15459
    /* verify provided arguments. The return value is an int holding the
15460
     * resulting length, so reject any len that cannot be represented as a
15461
     * non-negative int. This also prevents truncating size_t to int. */
15462
    if (buf == NULL || len > (size_t)WC_MAX_SINT_OF(int)) {
15463
        return 0; /* BAD_FUNC_ARG; */
15464
    }
15465
15466
    /* check to see if fits in existing length */
15467
    if (buf->length > len) {
15468
        buf->length = len;
15469
        return (int)len;
15470
    }
15471
15472
    /* check to see if fits in max buffer */
15473
    if (buf->max >= len) {
15474
        if (buf->data != NULL && zeroFill) {
15475
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
15476
        }
15477
        buf->length = len;
15478
        return (int)len;
15479
    }
15480
15481
    /* expand size, to handle growth */
15482
    mx = (len + 3) / 3 * 4;
15483
15484
#ifdef WOLFSSL_NO_REALLOC
15485
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
15486
    if (tmp != NULL && buf->data != NULL) {
15487
       /* only the existing content is valid in the old buffer; copying
15488
        * len_int (the new, larger size) would read past buf->max */
15489
       XMEMCPY(tmp, buf->data, buf->length);
15490
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
15491
       buf->data = NULL;
15492
    }
15493
#else
15494
    /* use realloc */
15495
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
15496
#endif
15497
15498
    if (tmp == NULL) {
15499
        return 0; /* ERR_R_MALLOC_FAILURE; */
15500
    }
15501
    buf->data = tmp;
15502
15503
    buf->max = mx;
15504
    if (zeroFill)
15505
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
15506
    buf->length = len;
15507
15508
    return (int)len;
15509
15510
}
15511
15512
/* returns length of buffer on success */
15513
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
15514
{
15515
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
15516
}
15517
15518
/* non-compat API returns length of buffer on success */
15519
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
15520
{
15521
    char* tmp;
15522
    size_t mx;
15523
15524
    /* verify provided arguments. The return value is an int, so reject any
15525
     * len that cannot be represented as a positive int. */
15526
    if (buf == NULL || len == 0 || len > (size_t)WC_MAX_SINT_OF(int)) {
15527
        return 0; /* BAD_FUNC_ARG; */
15528
    }
15529
15530
    if (len == buf->length)
15531
        return (int)len;
15532
15533
    if (len > buf->length)
15534
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
15535
15536
    /* expand size, to handle growth */
15537
    mx = (len + 3) / 3 * 4;
15538
15539
    /* We want to shrink the internal buffer */
15540
#ifdef WOLFSSL_NO_REALLOC
15541
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
15542
    if (tmp != NULL && buf->data != NULL)
15543
    {
15544
        XMEMCPY(tmp, buf->data, len);
15545
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
15546
        buf->data = NULL;
15547
    }
15548
#else
15549
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
15550
#endif
15551
15552
    if (tmp == NULL)
15553
        return 0;
15554
15555
    buf->data = tmp;
15556
    buf->length = len;
15557
    buf->max = mx;
15558
15559
    return (int)len;
15560
}
15561
15562
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
15563
{
15564
    if (buf) {
15565
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
15566
        buf->data = NULL;
15567
        buf->max = 0;
15568
        buf->length = 0;
15569
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
15570
    }
15571
}
15572
/* End Functions for openssl/buffer.h */
15573
15574
#endif /* OPENSSL_EXTRA */
15575
15576
/*******************************************************************************
15577
 * END OF BUF_MEM API
15578
 ******************************************************************************/
15579
15580
#define WOLFSSL_CONF_INCLUDED
15581
#include <src/conf.c>
15582
15583
/*******************************************************************************
15584
 * START OF RAND API
15585
 ******************************************************************************/
15586
15587
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
15588
static int wolfSSL_RAND_InitMutex(void)
15589
{
15590
#ifndef WOLFSSL_MUTEX_INITIALIZER
15591
    if (gRandMethodsInit == 0) {
15592
        if (wc_InitMutex(&gRandMethodMutex) != 0) {
15593
            WOLFSSL_MSG("Bad Init Mutex rand methods");
15594
            return BAD_MUTEX_E;
15595
        }
15596
        gRandMethodsInit = 1;
15597
    }
15598
#endif
15599
    return 0;
15600
}
15601
#endif
15602
15603
#ifdef OPENSSL_EXTRA
15604
15605
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
15606
    ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST))
15607
/* In older FIPS bundles add check for reseed here since it does not exist in
15608
 * the older random.c certified files. */
15609
static pid_t currentRandPid = 0;
15610
#endif
15611
15612
/* Checks if the global RNG has been created. If not then one is created.
15613
 *
15614
 * Returns WOLFSSL_SUCCESS when no error is encountered.
15615
 */
15616
int wolfSSL_RAND_Init(void)
15617
{
15618
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
15619
#ifdef HAVE_GLOBAL_RNG
15620
    if (wc_LockMutex(&globalRNGMutex) == 0) {
15621
        if (initGlobalRNG == 0) {
15622
            ret = wc_InitRng(&globalRNG);
15623
            if (ret == 0) {
15624
            #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
15625
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
15626
                 defined(HAVE_SELFTEST))
15627
15628
                currentRandPid = getpid();
15629
            #endif
15630
                initGlobalRNG = 1;
15631
                ret = WOLFSSL_SUCCESS;
15632
            }
15633
        }
15634
        else {
15635
            /* GlobalRNG is already initialized */
15636
            ret = WOLFSSL_SUCCESS;
15637
        }
15638
15639
        wc_UnLockMutex(&globalRNGMutex);
15640
    }
15641
#endif
15642
    return ret;
15643
}
15644
15645
15646
/* WOLFSSL_SUCCESS on ok */
15647
int wolfSSL_RAND_seed(const void* seed, int len)
15648
{
15649
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
15650
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
15651
        if (gRandMethods && gRandMethods->seed) {
15652
            int ret = gRandMethods->seed(seed, len);
15653
            wc_UnLockMutex(&gRandMethodMutex);
15654
            return ret;
15655
        }
15656
        wc_UnLockMutex(&gRandMethodMutex);
15657
    }
15658
#else
15659
    (void)seed;
15660
    (void)len;
15661
#endif
15662
15663
    /* Make sure global shared RNG (globalRNG) is initialized */
15664
    return wolfSSL_RAND_Init();
15665
}
15666
15667
15668
/* Returns the path for reading seed data from.
15669
 * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
15670
 *
15671
 * Note uses stdlib by default unless XGETENV macro is overwritten
15672
 *
15673
 * fname buffer to hold path
15674
 * len   length of fname buffer
15675
 *
15676
 * Returns a pointer to fname on success and NULL on failure
15677
 */
15678
const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
15679
{
15680
#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV)
15681
    char* rt;
15682
15683
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
15684
15685
    if (fname == NULL) {
15686
        return NULL;
15687
    }
15688
15689
    XMEMSET(fname, 0, len);
15690
15691
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
15692
    if ((rt = XGETENV("RANDFILE")) != NULL) {
15693
        if (len > XSTRLEN(rt)) {
15694
            XMEMCPY(fname, rt, XSTRLEN(rt));
15695
        }
15696
        else {
15697
            WOLFSSL_MSG("RANDFILE too large for buffer");
15698
            rt = NULL;
15699
        }
15700
    }
15701
/* // NOLINTEND(concurrency-mt-unsafe) */
15702
15703
    /* $RANDFILE was not set or is too large, check $HOME */
15704
    if (rt == NULL) {
15705
        const char ap[] = "/.rnd";
15706
15707
        WOLFSSL_MSG("Environment variable RANDFILE not set");
15708
15709
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
15710
        if ((rt = XGETENV("HOME")) == NULL) {
15711
            #ifdef XALTHOMEVARNAME
15712
            if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) {
15713
                WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME
15714
                            " not set");
15715
                return NULL;
15716
            }
15717
            #else
15718
            WOLFSSL_MSG("Environment variable HOME not set");
15719
            return NULL;
15720
            #endif
15721
        }
15722
/* // NOLINTEND(concurrency-mt-unsafe) */
15723
15724
        if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
15725
            fname[0] = '\0';
15726
            XSTRNCAT(fname, rt, len);
15727
            XSTRNCAT(fname, ap, len - XSTRLEN(rt));
15728
            return fname;
15729
        }
15730
        else {
15731
            WOLFSSL_MSG("Path too large for buffer");
15732
            return NULL;
15733
        }
15734
    }
15735
15736
    return fname;
15737
#else
15738
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
15739
    WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, "
15740
                "not compiled in");
15741
    (void)fname;
15742
    (void)len;
15743
    return NULL;
15744
#endif
15745
}
15746
15747
15748
#ifndef WOLFSSL_RAND_WRITE_FILE_BUF_SZ
15749
#define WOLFSSL_RAND_WRITE_FILE_BUF_SZ 1024
15750
#endif
15751
/* Writes WOLFSSL_RAND_WRITE_FILE_BUF_SZ bytes (1024 by default) from the RNG
15752
 * to the given file name.
15753
 *
15754
 * fname name of file to write to
15755
 *
15756
 * Returns the number of bytes written
15757
 */
15758
int wolfSSL_RAND_write_file(const char* fname)
15759
{
15760
    int bytes = 0;
15761
15762
    WOLFSSL_ENTER("wolfSSL_RAND_write_file");
15763
15764
    if (fname == NULL) {
15765
        return WOLFSSL_FAILURE;
15766
    }
15767
15768
#ifndef NO_FILESYSTEM
15769
    {
15770
    #ifndef WOLFSSL_SMALL_STACK
15771
        unsigned char buf[WOLFSSL_RAND_WRITE_FILE_BUF_SZ];
15772
    #else
15773
        unsigned char* buf = (unsigned char *)XMALLOC(
15774
            WOLFSSL_RAND_WRITE_FILE_BUF_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15775
        if (buf == NULL) {
15776
            WOLFSSL_MSG("malloc failed");
15777
            return WOLFSSL_FAILURE;
15778
        }
15779
    #endif
15780
        bytes = WOLFSSL_RAND_WRITE_FILE_BUF_SZ;
15781
15782
        if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
15783
            WOLFSSL_MSG("No RNG to use");
15784
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15785
            return 0;
15786
        }
15787
15788
        if (wc_LockMutex(&globalRNGMutex) != 0) {
15789
            WOLFSSL_MSG("Bad Lock Mutex rng");
15790
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15791
            return 0;
15792
        }
15793
15794
        if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) {
15795
            wc_UnLockMutex(&globalRNGMutex);
15796
            WOLFSSL_MSG("Error generating random buffer");
15797
            bytes = 0;
15798
        }
15799
        else {
15800
            XFILE f;
15801
15802
            wc_UnLockMutex(&globalRNGMutex);
15803
15804
        #ifdef WOLFSSL_CHECK_MEM_ZERO
15805
            wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
15806
        #endif
15807
15808
            f = XFOPEN(fname, "wb");
15809
            if (f == XBADFILE) {
15810
                WOLFSSL_MSG("Error opening the file");
15811
                bytes = 0;
15812
            }
15813
            else {
15814
                size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f);
15815
                bytes = (int)bytes_written;
15816
                XFCLOSE(f);
15817
            }
15818
        }
15819
        /* wipe the whole buffer, not just (word32)bytes: error paths set
15820
         * bytes = 0 but the buffer may still hold generated random data */
15821
        ForceZero(buf, WOLFSSL_RAND_WRITE_FILE_BUF_SZ);
15822
    #ifdef WOLFSSL_SMALL_STACK
15823
        XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15824
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
15825
        wc_MemZero_Check(buf, sizeof(buf));
15826
    #endif
15827
    }
15828
#endif
15829
15830
    return bytes;
15831
}
15832
15833
#ifndef FREERTOS_TCP
15834
15835
/* These constant values are protocol values made by egd */
15836
#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \
15837
    !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \
15838
    defined(HAVE_SYS_UN_H)
15839
    #define WOLFSSL_EGD_NBLOCK 0x01
15840
    #include <sys/un.h>
15841
#endif
15842
15843
/* This collects entropy from the path nm and seeds the global PRNG with it.
15844
 *
15845
 * nm is the file path to the egd server
15846
 *
15847
 * Returns the number of bytes read.
15848
 */
15849
int wolfSSL_RAND_egd(const char* nm)
15850
{
15851
#ifdef WOLFSSL_EGD_NBLOCK
15852
    struct sockaddr_un rem;
15853
    int fd;
15854
    int ret = WOLFSSL_SUCCESS;
15855
    word32 bytes = 0;
15856
    word32 idx   = 0;
15857
#ifndef WOLFSSL_SMALL_STACK
15858
    unsigned char buf[256];
15859
#else
15860
    unsigned char* buf;
15861
    buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15862
    if (buf == NULL) {
15863
        WOLFSSL_MSG("Not enough memory");
15864
        return WOLFSSL_FATAL_ERROR;
15865
    }
15866
#endif
15867
15868
    XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
15869
    if (nm == NULL) {
15870
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15871
        return WOLFSSL_FATAL_ERROR;
15872
    }
15873
15874
    fd = wc_socket_cloexec(AF_UNIX, SOCK_STREAM, 0);
15875
    if (fd < 0) {
15876
        WOLFSSL_MSG("Error creating socket");
15877
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15878
        return WOLFSSL_FATAL_ERROR;
15879
    }
15880
    rem.sun_family = AF_UNIX;
15881
    XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
15882
    rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
15883
15884
    /* connect to egd server */
15885
    if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
15886
        WOLFSSL_MSG("error connecting to egd server");
15887
        ret = WOLFSSL_FATAL_ERROR;
15888
    }
15889
15890
#ifdef WOLFSSL_CHECK_MEM_ZERO
15891
    if (ret == WOLFSSL_SUCCESS) {
15892
        wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
15893
    }
15894
#endif
15895
    while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
15896
        buf[idx]     = WOLFSSL_EGD_NBLOCK;
15897
        buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
15898
        ret = (int)write(fd, buf + idx, 2);
15899
        if (ret != 2) {
15900
            if (errno == EAGAIN) {
15901
                ret = WOLFSSL_SUCCESS;
15902
                continue;
15903
            }
15904
            WOLFSSL_MSG("error requesting entropy from egd server");
15905
            ret = WOLFSSL_FATAL_ERROR;
15906
            break;
15907
        }
15908
15909
        /* attempting to read */
15910
        buf[idx] = 0;
15911
        ret = (int)read(fd, buf + idx, 256 - bytes);
15912
        if (ret == 0) {
15913
            WOLFSSL_MSG("error reading entropy from egd server");
15914
            ret = WOLFSSL_FATAL_ERROR;
15915
            break;
15916
        }
15917
        if (ret > 0 && buf[idx] > 0) {
15918
            bytes += buf[idx]; /* egd stores amount sent in first byte */
15919
            if (bytes + idx > 255 || buf[idx] > ret) {
15920
                WOLFSSL_MSG("Buffer error");
15921
                ret = WOLFSSL_FATAL_ERROR;
15922
                break;
15923
            }
15924
            XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
15925
            idx = bytes;
15926
            ret = WOLFSSL_SUCCESS;
15927
            if (bytes >= 255) {
15928
                break;
15929
            }
15930
        }
15931
        else {
15932
            if (errno == EAGAIN || errno == EINTR) {
15933
                WOLFSSL_MSG("EGD would read");
15934
                ret = WOLFSSL_SUCCESS; /* try again */
15935
            }
15936
            else if (buf[idx] == 0) {
15937
                /* if egd returned 0 then there is no more entropy to be had.
15938
                   Do not try more reads. */
15939
                ret = WOLFSSL_SUCCESS;
15940
                break;
15941
            }
15942
            else {
15943
                WOLFSSL_MSG("Error with read");
15944
                ret = WOLFSSL_FATAL_ERROR;
15945
            }
15946
        }
15947
    }
15948
15949
    if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
15950
        /* call to check global RNG is created */
15951
        if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
15952
            WOLFSSL_MSG("Error with initializing global RNG structure");
15953
            ret = WOLFSSL_FATAL_ERROR;
15954
        }
15955
        else if (wc_LockMutex(&globalRNGMutex) != 0) {
15956
            WOLFSSL_MSG("Bad Lock Mutex rng");
15957
            ret = WOLFSSL_FATAL_ERROR;
15958
        }
15959
        else {
15960
            if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
15961
                    != 0) {
15962
                WOLFSSL_MSG("Error with reseeding DRBG structure");
15963
                ret = WOLFSSL_FATAL_ERROR;
15964
            }
15965
            wc_UnLockMutex(&globalRNGMutex);
15966
15967
            #ifdef SHOW_SECRETS
15968
            /* print out entropy found only when no error occurred */
15969
            if (ret == WOLFSSL_SUCCESS) {
15970
                word32 i;
15971
                printf("EGD Entropy = ");
15972
                for (i = 0; i < bytes; i++) {
15973
                    printf("%02X", buf[i]);
15974
                }
15975
                printf("\n");
15976
            }
15977
            #endif
15978
        }
15979
    }
15980
15981
    ForceZero(buf, bytes);
15982
#ifdef WOLFSSL_SMALL_STACK
15983
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
15984
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
15985
    wc_MemZero_Check(buf, 256);
15986
#endif
15987
    close(fd);
15988
15989
    if (ret == WOLFSSL_SUCCESS) {
15990
        return (int)bytes;
15991
    }
15992
    else {
15993
        return ret;
15994
    }
15995
#else
15996
    WOLFSSL_MSG("Type of socket needed is not available");
15997
    WOLFSSL_MSG("\tor using mode where DRBG API is not available");
15998
    (void)nm;
15999
16000
    return WOLFSSL_FATAL_ERROR;
16001
#endif /* WOLFSSL_EGD_NBLOCK */
16002
}
16003
16004
#endif /* !FREERTOS_TCP */
16005
16006
void wolfSSL_RAND_Cleanup(void)
16007
{
16008
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16009
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
16010
        if (gRandMethods && gRandMethods->cleanup)
16011
            gRandMethods->cleanup();
16012
        wc_UnLockMutex(&gRandMethodMutex);
16013
    }
16014
16015
    #ifndef WOLFSSL_MUTEX_INITIALIZER
16016
    if (wc_FreeMutex(&gRandMethodMutex) == 0)
16017
        gRandMethodsInit = 0;
16018
    #endif
16019
#endif
16020
#ifdef HAVE_GLOBAL_RNG
16021
    if (wc_LockMutex(&globalRNGMutex) == 0) {
16022
        if (initGlobalRNG) {
16023
            wc_FreeRng(&globalRNG);
16024
            initGlobalRNG = 0;
16025
        }
16026
        wc_UnLockMutex(&globalRNGMutex);
16027
    }
16028
#endif
16029
}
16030
16031
/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise
16032
 * WOLFSSL_FAILURE */
16033
int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
16034
{
16035
    int ret;
16036
    int hash;
16037
    byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */
16038
16039
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16040
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
16041
        if (gRandMethods && gRandMethods->pseudorand) {
16042
            ret = gRandMethods->pseudorand(buf, num);
16043
            wc_UnLockMutex(&gRandMethodMutex);
16044
            return ret;
16045
        }
16046
        wc_UnLockMutex(&gRandMethodMutex);
16047
    }
16048
#endif
16049
16050
#ifdef WOLFSSL_HAVE_PRF
16051
    #ifndef NO_SHA256
16052
    hash = WC_SHA256;
16053
    #elif defined(WOLFSSL_SHA384)
16054
    hash = WC_SHA384;
16055
    #elif !defined(NO_SHA)
16056
    hash = WC_SHA;
16057
    #elif !defined(NO_MD5)
16058
    hash = WC_MD5;
16059
    #endif
16060
16061
    /* get secret value from source of entropy */
16062
    ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
16063
16064
    /* uses input buffer to seed for pseudo random number generation, each
16065
     * thread will potentially have different results this way */
16066
    if (ret == WOLFSSL_SUCCESS) {
16067
        PRIVATE_KEY_UNLOCK();
16068
        ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
16069
                hash, NULL, INVALID_DEVID);
16070
        PRIVATE_KEY_LOCK();
16071
        ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
16072
    }
16073
#else
16074
    /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
16075
    ret = wolfSSL_RAND_bytes(buf, num);
16076
    (void)hash;
16077
    (void)secret;
16078
#endif
16079
    return ret;
16080
}
16081
16082
/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0
16083
 * on failure */
16084
int wolfSSL_RAND_bytes(unsigned char* buf, int num)
16085
{
16086
    int     ret = 0;
16087
    WC_RNG* rng = NULL;
16088
    WC_DECLARE_VAR(tmpRNG, WC_RNG, 1, 0);
16089
    int initTmpRng = 0;
16090
#ifdef HAVE_GLOBAL_RNG
16091
    int used_global = 0;
16092
#endif
16093
16094
    WOLFSSL_ENTER("wolfSSL_RAND_bytes");
16095
    /* sanity check */
16096
    if (buf == NULL || num < 0)
16097
        /* return code compliant with OpenSSL */
16098
        return 0;
16099
16100
    /* if a RAND callback has been set try and use it */
16101
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16102
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
16103
        if (gRandMethods && gRandMethods->bytes) {
16104
            ret = gRandMethods->bytes(buf, num);
16105
            wc_UnLockMutex(&gRandMethodMutex);
16106
            return ret;
16107
        }
16108
        wc_UnLockMutex(&gRandMethodMutex);
16109
    }
16110
#endif
16111
#ifdef HAVE_GLOBAL_RNG
16112
    if (initGlobalRNG) {
16113
        if (wc_LockMutex(&globalRNGMutex) != 0) {
16114
            WOLFSSL_MSG("Bad Lock Mutex rng");
16115
            return ret;
16116
        }
16117
        /* the above access to initGlobalRNG is racey -- recheck it now that we
16118
         * have the lock.
16119
         */
16120
        if (initGlobalRNG) {
16121
        #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
16122
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
16123
                 defined(HAVE_SELFTEST))
16124
            pid_t p;
16125
16126
            p = getpid();
16127
            if (p != currentRandPid) {
16128
                wc_UnLockMutex(&globalRNGMutex);
16129
                if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) {
16130
                    WOLFSSL_MSG("Issue with check pid and reseed");
16131
                    ret = WOLFSSL_FAILURE;
16132
                }
16133
16134
                /* reclaim lock after wolfSSL_RAND_poll */
16135
                if (wc_LockMutex(&globalRNGMutex) != 0) {
16136
                    WOLFSSL_MSG("Bad Lock Mutex rng");
16137
                    return ret;
16138
                }
16139
                currentRandPid = p;
16140
            }
16141
        #endif
16142
            rng = &globalRNG;
16143
            used_global = 1;
16144
        }
16145
        else {
16146
            wc_UnLockMutex(&globalRNGMutex);
16147
        }
16148
    }
16149
16150
    if (used_global == 0)
16151
#endif
16152
    {
16153
        WC_ALLOC_VAR_EX(tmpRNG, WC_RNG, 1, NULL, DYNAMIC_TYPE_RNG,
16154
            return ret);
16155
        if (wc_InitRng(tmpRNG) == 0) {
16156
            rng = tmpRNG;
16157
            initTmpRng = 1;
16158
        }
16159
    }
16160
    if (rng) {
16161
        /* handles size greater than RNG_MAX_BLOCK_LEN */
16162
        int blockCount = num / RNG_MAX_BLOCK_LEN;
16163
16164
        while (blockCount--) {
16165
            ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
16166
            if (ret != 0) {
16167
                WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
16168
                break;
16169
            }
16170
            num -= RNG_MAX_BLOCK_LEN;
16171
            buf += RNG_MAX_BLOCK_LEN;
16172
        }
16173
16174
        if (ret == 0 && num)
16175
            ret = wc_RNG_GenerateBlock(rng, buf, (word32)num);
16176
16177
        if (ret != 0)
16178
            WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
16179
        else
16180
            ret = WOLFSSL_SUCCESS;
16181
    }
16182
16183
#ifdef HAVE_GLOBAL_RNG
16184
    if (used_global == 1)
16185
        wc_UnLockMutex(&globalRNGMutex);
16186
#endif
16187
    if (initTmpRng)
16188
        wc_FreeRng(tmpRNG);
16189
    WC_FREE_VAR_EX(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
16190
16191
    return ret;
16192
}
16193
16194
16195
int wolfSSL_RAND_poll(void)
16196
{
16197
    byte  entropy[16];
16198
    int  ret = 0;
16199
    word32 entropy_sz = 16;
16200
16201
    WOLFSSL_ENTER("wolfSSL_RAND_poll");
16202
    if (initGlobalRNG == 0){
16203
        WOLFSSL_MSG("Global RNG no Init");
16204
        return  WOLFSSL_FAILURE;
16205
    }
16206
16207
    /* lock intentionally covers wc_GenerateSeed as well, since it writes
16208
     * globalRNG.seed; do not narrow this scope or the seed write races */
16209
    if (wc_LockMutex(&globalRNGMutex) != 0) {
16210
        WOLFSSL_MSG("Bad Lock Mutex rng");
16211
        return WOLFSSL_FAILURE;
16212
    }
16213
16214
    ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
16215
    if (ret != 0) {
16216
        WOLFSSL_MSG("Bad wc_GenerateSeed");
16217
        ret = WOLFSSL_FAILURE;
16218
    }
16219
    else {
16220
#ifdef HAVE_HASHDRBG
16221
        ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
16222
        if (ret != 0) {
16223
            WOLFSSL_MSG("Error reseeding DRBG");
16224
            ret = WOLFSSL_FAILURE;
16225
        }
16226
        else {
16227
            ret = WOLFSSL_SUCCESS;
16228
        }
16229
#elif defined(HAVE_INTEL_RDRAND)
16230
        WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without "
16231
                    "HAVE_HASHDRBG");
16232
        ret = WOLFSSL_SUCCESS;
16233
#else
16234
        WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set");
16235
        ret = WOLFSSL_FAILURE;
16236
#endif
16237
    }
16238
16239
    wc_UnLockMutex(&globalRNGMutex);
16240
16241
    return ret;
16242
}
16243
16244
    /* If a valid struct is provided with function pointers, will override
16245
       RAND_seed, bytes, cleanup, add, pseudo_bytes and status.  If a NULL
16246
       pointer is passed in, it will cancel any previous function overrides.
16247
16248
       Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
16249
    int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
16250
    {
16251
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16252
        if (wolfSSL_RAND_InitMutex() == 0 &&
16253
                wc_LockMutex(&gRandMethodMutex) == 0) {
16254
            gRandMethods = methods;
16255
            wc_UnLockMutex(&gRandMethodMutex);
16256
            return WOLFSSL_SUCCESS;
16257
        }
16258
    #else
16259
        (void)methods;
16260
    #endif
16261
        return WOLFSSL_FAILURE;
16262
    }
16263
16264
    /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
16265
    int wolfSSL_RAND_status(void)
16266
    {
16267
        int ret = WOLFSSL_SUCCESS;
16268
        int useGlobalRng = 1;
16269
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16270
        if (wolfSSL_RAND_InitMutex() == 0 &&
16271
                wc_LockMutex(&gRandMethodMutex) == 0) {
16272
            if (gRandMethods && gRandMethods->status) {
16273
                ret = gRandMethods->status();
16274
                useGlobalRng = 0;
16275
            }
16276
            wc_UnLockMutex(&gRandMethodMutex);
16277
        }
16278
        else {
16279
            ret = WOLFSSL_FAILURE;
16280
            useGlobalRng = 0;
16281
        }
16282
    #endif
16283
16284
        /* Drive the global RNG so init / DRBG state failures (mutex
16285
         * acquisition, reseed required, corrupted state) surface to the
16286
         * caller. DRBG output is deterministic between reseeds, so this
16287
         * does not directly probe the entropy source. */
16288
    #ifdef HAVE_GLOBAL_RNG
16289
        if (useGlobalRng) {
16290
            if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
16291
                ret = WOLFSSL_FAILURE;
16292
            }
16293
            else if (wc_LockMutex(&globalRNGMutex) != 0) {
16294
                ret = WOLFSSL_FAILURE;
16295
            }
16296
            else {
16297
                byte b = 0;
16298
                int genRet = wc_RNG_GenerateBlock(&globalRNG, &b, 1);
16299
                wc_UnLockMutex(&globalRNGMutex);
16300
                ForceZero(&b, 1);
16301
                if (genRet != 0)
16302
                    ret = WOLFSSL_FAILURE;
16303
            }
16304
        }
16305
    #endif
16306
        (void)useGlobalRng;
16307
        return ret;
16308
    }
16309
16310
    void wolfSSL_RAND_add(const void* add, int len, double entropy)
16311
    {
16312
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
16313
        if (wolfSSL_RAND_InitMutex() == 0 &&
16314
                wc_LockMutex(&gRandMethodMutex) == 0) {
16315
            if (gRandMethods && gRandMethods->add) {
16316
                /* callback has return code, but RAND_add does not */
16317
                (void)gRandMethods->add(add, len, entropy);
16318
            }
16319
            wc_UnLockMutex(&gRandMethodMutex);
16320
        }
16321
    #else
16322
        /* wolfSSL seeds/adds internally, use explicit RNG if you want
16323
           to take control */
16324
        (void)add;
16325
        (void)len;
16326
        (void)entropy;
16327
    #endif
16328
    }
16329
16330
16331
#ifndef NO_WOLFSSL_STUB
16332
void wolfSSL_RAND_screen(void)
16333
{
16334
    WOLFSSL_STUB("RAND_screen");
16335
}
16336
#endif
16337
16338
#ifndef WOLFSSL_RAND_LOAD_FILE_BUF_SZ
16339
#define WOLFSSL_RAND_LOAD_FILE_BUF_SZ 256
16340
#endif
16341
#ifndef WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
16342
#define WOLFSSL_RAND_LOAD_FILE_MAX_BYTES (1L << 20)
16343
#endif
16344
16345
int wolfSSL_RAND_load_file(const char* fname, long len)
16346
{
16347
#if !defined(NO_FILESYSTEM) && defined(HAVE_HASHDRBG)
16348
    XFILE  f;
16349
    long   maxBytes;
16350
    long   readSoFar = 0;
16351
    int    ret = 0;
16352
#ifndef WOLFSSL_SMALL_STACK
16353
    unsigned char buf[WOLFSSL_RAND_LOAD_FILE_BUF_SZ];
16354
#else
16355
    unsigned char* buf;
16356
#endif
16357
16358
    WOLFSSL_ENTER("wolfSSL_RAND_load_file");
16359
16360
    if (fname == NULL)
16361
        return WOLFSSL_FATAL_ERROR;
16362
16363
    /* OpenSSL semantics: RAND_load_file(file, -1) reads up to an
16364
     * implementation-defined maximum. WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
16365
     * caps the read so callers passing -1 to ingest a seed file aren't
16366
     * silently truncated at a small default. */
16367
    maxBytes = (len < 0) ? WOLFSSL_RAND_LOAD_FILE_MAX_BYTES : len;
16368
    if (maxBytes == 0)
16369
        return 0;
16370
16371
    f = XFOPEN(fname, "rb");
16372
    if (f == XBADFILE) {
16373
        WOLFSSL_MSG("RAND_load_file: cannot open file");
16374
        return WOLFSSL_FATAL_ERROR;
16375
    }
16376
16377
#ifdef WOLFSSL_SMALL_STACK
16378
    buf = (unsigned char*)XMALLOC(WOLFSSL_RAND_LOAD_FILE_BUF_SZ, NULL,
16379
        DYNAMIC_TYPE_TMP_BUFFER);
16380
    if (buf == NULL) {
16381
        XFCLOSE(f);
16382
        return WOLFSSL_FATAL_ERROR;
16383
    }
16384
#endif
16385
#ifdef WOLFSSL_CHECK_MEM_ZERO
16386
    wc_MemZero_Add("wolfSSL_RAND_load_file buf", buf,
16387
        WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16388
#endif
16389
16390
    if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
16391
        WOLFSSL_MSG("RAND_load_file: global RNG not available");
16392
        ret = WOLFSSL_FATAL_ERROR;
16393
        goto cleanup;
16394
    }
16395
16396
    while (readSoFar < maxBytes) {
16397
        size_t toRead = (size_t)((maxBytes - readSoFar) <
16398
                WOLFSSL_RAND_LOAD_FILE_BUF_SZ
16399
            ? (maxBytes - readSoFar) : WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16400
        size_t n = XFREAD(buf, 1, toRead, f);
16401
        if (n == 0)
16402
            break;
16403
        if (wc_LockMutex(&globalRNGMutex) != 0) {
16404
            ret = WOLFSSL_FATAL_ERROR;
16405
            break;
16406
        }
16407
        if (wc_RNG_DRBG_Reseed(&globalRNG, buf, (word32)n) != 0) {
16408
            wc_UnLockMutex(&globalRNGMutex);
16409
            WOLFSSL_MSG("RAND_load_file: DRBG reseed failed");
16410
            ret = WOLFSSL_FATAL_ERROR;
16411
            break;
16412
        }
16413
        wc_UnLockMutex(&globalRNGMutex);
16414
        readSoFar += (long)n;
16415
    }
16416
16417
cleanup:
16418
    XFCLOSE(f);
16419
    ForceZero(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16420
#ifdef WOLFSSL_SMALL_STACK
16421
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
16422
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
16423
    wc_MemZero_Check(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
16424
#endif
16425
16426
    if (ret < 0)
16427
        return WOLFSSL_FATAL_ERROR;
16428
    return (int)readSoFar;
16429
#else
16430
    /* Without HAVE_HASHDRBG / filesystem support there is no way to feed
16431
     * external entropy to the wolfCrypt RNG; return success so callers
16432
     * in those configurations are not broken. */
16433
    (void)fname;
16434
    if (len == -1)
16435
        return 1024;
16436
    return (int)len;
16437
#endif
16438
}
16439
16440
#endif /* OPENSSL_EXTRA */
16441
16442
/*******************************************************************************
16443
 * END OF RAND API
16444
 ******************************************************************************/
16445
16446
/*******************************************************************************
16447
 * START OF EVP_CIPHER API
16448
 ******************************************************************************/
16449
16450
#ifdef OPENSSL_EXTRA
16451
16452
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
16453
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
16454
    {
16455
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
16456
16457
        if (ctx == NULL) {
16458
            WOLFSSL_MSG("Bad function argument");
16459
            return WOLFSSL_FATAL_ERROR;
16460
        }
16461
16462
        switch (ctx->cipherType) {
16463
#ifndef NO_AES
16464
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
16465
            case WC_AES_128_CBC_TYPE :
16466
            case WC_AES_192_CBC_TYPE :
16467
            case WC_AES_256_CBC_TYPE :
16468
                WOLFSSL_MSG("AES CBC");
16469
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16470
                break;
16471
#endif
16472
#ifdef HAVE_AESGCM
16473
            case WC_AES_128_GCM_TYPE :
16474
            case WC_AES_192_GCM_TYPE :
16475
            case WC_AES_256_GCM_TYPE :
16476
                WOLFSSL_MSG("AES GCM");
16477
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16478
                break;
16479
#endif /* HAVE_AESGCM */
16480
#ifdef HAVE_AESCCM
16481
            case WC_AES_128_CCM_TYPE :
16482
            case WC_AES_192_CCM_TYPE :
16483
            case WC_AES_256_CCM_TYPE :
16484
                WOLFSSL_MSG("AES CCM");
16485
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
16486
                break;
16487
#endif /* HAVE_AESCCM */
16488
#ifdef HAVE_AES_ECB
16489
            case WC_AES_128_ECB_TYPE :
16490
            case WC_AES_192_ECB_TYPE :
16491
            case WC_AES_256_ECB_TYPE :
16492
                WOLFSSL_MSG("AES ECB");
16493
                break;
16494
#endif
16495
#ifdef WOLFSSL_AES_COUNTER
16496
            case WC_AES_128_CTR_TYPE :
16497
            case WC_AES_192_CTR_TYPE :
16498
            case WC_AES_256_CTR_TYPE :
16499
                WOLFSSL_MSG("AES CTR");
16500
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
16501
                break;
16502
#endif /* WOLFSSL_AES_COUNTER */
16503
#ifdef WOLFSSL_AES_CFB
16504
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
16505
            case WC_AES_128_CFB1_TYPE:
16506
            case WC_AES_192_CFB1_TYPE:
16507
            case WC_AES_256_CFB1_TYPE:
16508
                WOLFSSL_MSG("AES CFB1");
16509
                break;
16510
            case WC_AES_128_CFB8_TYPE:
16511
            case WC_AES_192_CFB8_TYPE:
16512
            case WC_AES_256_CFB8_TYPE:
16513
                WOLFSSL_MSG("AES CFB8");
16514
                break;
16515
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
16516
            case WC_AES_128_CFB128_TYPE:
16517
            case WC_AES_192_CFB128_TYPE:
16518
            case WC_AES_256_CFB128_TYPE:
16519
                WOLFSSL_MSG("AES CFB128");
16520
                break;
16521
#endif /* WOLFSSL_AES_CFB */
16522
#if defined(WOLFSSL_AES_OFB)
16523
            case WC_AES_128_OFB_TYPE:
16524
            case WC_AES_192_OFB_TYPE:
16525
            case WC_AES_256_OFB_TYPE:
16526
                WOLFSSL_MSG("AES OFB");
16527
                break;
16528
#endif /* WOLFSSL_AES_OFB */
16529
#ifdef WOLFSSL_AES_XTS
16530
            case WC_AES_128_XTS_TYPE:
16531
            case WC_AES_256_XTS_TYPE:
16532
                WOLFSSL_MSG("AES XTS");
16533
                break;
16534
#endif /* WOLFSSL_AES_XTS */
16535
#endif /* NO_AES */
16536
16537
#ifdef HAVE_ARIA
16538
            case WC_ARIA_128_GCM_TYPE :
16539
            case WC_ARIA_192_GCM_TYPE :
16540
            case WC_ARIA_256_GCM_TYPE :
16541
                WOLFSSL_MSG("ARIA GCM");
16542
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
16543
                break;
16544
#endif /* HAVE_ARIA */
16545
16546
#ifndef NO_DES3
16547
            case WC_DES_CBC_TYPE :
16548
                WOLFSSL_MSG("DES CBC");
16549
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
16550
                break;
16551
16552
            case WC_DES_EDE3_CBC_TYPE :
16553
                WOLFSSL_MSG("DES EDE3 CBC");
16554
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
16555
                break;
16556
#endif
16557
#ifdef WOLFSSL_DES_ECB
16558
            case WC_DES_ECB_TYPE :
16559
                WOLFSSL_MSG("DES ECB");
16560
                break;
16561
            case WC_DES_EDE3_ECB_TYPE :
16562
                WOLFSSL_MSG("DES3 ECB");
16563
                break;
16564
#endif
16565
            case WC_ARC4_TYPE :
16566
                WOLFSSL_MSG("ARC4");
16567
                break;
16568
16569
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
16570
            case WC_CHACHA20_POLY1305_TYPE:
16571
                break;
16572
#endif
16573
16574
#ifdef HAVE_CHACHA
16575
            case WC_CHACHA20_TYPE:
16576
                break;
16577
#endif
16578
16579
#ifdef WOLFSSL_SM4_ECB
16580
            case WC_SM4_ECB_TYPE:
16581
                break;
16582
#endif
16583
#ifdef WOLFSSL_SM4_CBC
16584
            case WC_SM4_CBC_TYPE:
16585
                WOLFSSL_MSG("SM4 CBC");
16586
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16587
                break;
16588
#endif
16589
#ifdef WOLFSSL_SM4_CTR
16590
            case WC_SM4_CTR_TYPE:
16591
                WOLFSSL_MSG("SM4 CTR");
16592
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16593
                break;
16594
#endif
16595
#ifdef WOLFSSL_SM4_GCM
16596
            case WC_SM4_GCM_TYPE:
16597
                WOLFSSL_MSG("SM4 GCM");
16598
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16599
                break;
16600
#endif
16601
#ifdef WOLFSSL_SM4_CCM
16602
            case WC_SM4_CCM_TYPE:
16603
                WOLFSSL_MSG("SM4 CCM");
16604
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
16605
                break;
16606
#endif
16607
16608
            case WC_NULL_CIPHER_TYPE :
16609
                WOLFSSL_MSG("NULL");
16610
                break;
16611
16612
            default: {
16613
                WOLFSSL_MSG("bad type");
16614
                return WOLFSSL_FATAL_ERROR;
16615
            }
16616
        }
16617
        return WOLFSSL_SUCCESS;
16618
    }
16619
16620
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
16621
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
16622
    {
16623
16624
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
16625
16626
        if (ctx == NULL) {
16627
            WOLFSSL_MSG("Bad function argument");
16628
            return WOLFSSL_FATAL_ERROR;
16629
        }
16630
16631
        switch (ctx->cipherType) {
16632
16633
#ifndef NO_AES
16634
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
16635
            case WC_AES_128_CBC_TYPE :
16636
            case WC_AES_192_CBC_TYPE :
16637
            case WC_AES_256_CBC_TYPE :
16638
                WOLFSSL_MSG("AES CBC");
16639
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16640
                break;
16641
#endif
16642
#ifdef HAVE_AESGCM
16643
            case WC_AES_128_GCM_TYPE :
16644
            case WC_AES_192_GCM_TYPE :
16645
            case WC_AES_256_GCM_TYPE :
16646
                WOLFSSL_MSG("AES GCM");
16647
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16648
                break;
16649
#endif
16650
#ifdef HAVE_AES_ECB
16651
            case WC_AES_128_ECB_TYPE :
16652
            case WC_AES_192_ECB_TYPE :
16653
            case WC_AES_256_ECB_TYPE :
16654
                WOLFSSL_MSG("AES ECB");
16655
                break;
16656
#endif
16657
#ifdef WOLFSSL_AES_COUNTER
16658
            case WC_AES_128_CTR_TYPE :
16659
            case WC_AES_192_CTR_TYPE :
16660
            case WC_AES_256_CTR_TYPE :
16661
                WOLFSSL_MSG("AES CTR");
16662
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
16663
                break;
16664
#endif
16665
16666
#endif /* NO_AES */
16667
16668
#ifdef HAVE_ARIA
16669
            case WC_ARIA_128_GCM_TYPE :
16670
            case WC_ARIA_192_GCM_TYPE :
16671
            case WC_ARIA_256_GCM_TYPE :
16672
                WOLFSSL_MSG("ARIA GCM");
16673
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
16674
                break;
16675
#endif /* HAVE_ARIA */
16676
16677
#ifndef NO_DES3
16678
            case WC_DES_CBC_TYPE :
16679
                WOLFSSL_MSG("DES CBC");
16680
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
16681
                break;
16682
16683
            case WC_DES_EDE3_CBC_TYPE :
16684
                WOLFSSL_MSG("DES EDE3 CBC");
16685
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
16686
                break;
16687
#endif
16688
#ifdef WOLFSSL_DES_ECB
16689
            case WC_DES_ECB_TYPE :
16690
                WOLFSSL_MSG("DES ECB");
16691
                break;
16692
            case WC_DES_EDE3_ECB_TYPE :
16693
                WOLFSSL_MSG("DES3 ECB");
16694
                break;
16695
#endif
16696
16697
            case WC_ARC4_TYPE :
16698
                WOLFSSL_MSG("ARC4");
16699
                break;
16700
16701
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
16702
            case WC_CHACHA20_POLY1305_TYPE:
16703
                break;
16704
#endif
16705
16706
#ifdef HAVE_CHACHA
16707
            case WC_CHACHA20_TYPE:
16708
                break;
16709
#endif
16710
16711
#ifdef WOLFSSL_SM4_ECB
16712
            case WC_SM4_ECB_TYPE:
16713
                break;
16714
#endif
16715
#ifdef WOLFSSL_SM4_CBC
16716
            case WC_SM4_CBC_TYPE:
16717
                WOLFSSL_MSG("SM4 CBC");
16718
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16719
                break;
16720
#endif
16721
#ifdef WOLFSSL_SM4_CTR
16722
            case WC_SM4_CTR_TYPE:
16723
                WOLFSSL_MSG("SM4 CTR");
16724
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16725
                break;
16726
#endif
16727
#ifdef WOLFSSL_SM4_GCM
16728
            case WC_SM4_GCM_TYPE:
16729
                WOLFSSL_MSG("SM4 GCM");
16730
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16731
                break;
16732
#endif
16733
#ifdef WOLFSSL_SM4_CCM
16734
            case WC_SM4_CCM_TYPE:
16735
                WOLFSSL_MSG("SM4 CCM");
16736
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
16737
                break;
16738
#endif
16739
16740
            case WC_NULL_CIPHER_TYPE :
16741
                WOLFSSL_MSG("NULL");
16742
                break;
16743
16744
            default: {
16745
                WOLFSSL_MSG("bad type");
16746
                return WOLFSSL_FATAL_ERROR;
16747
            }
16748
        }
16749
        return WOLFSSL_SUCCESS;
16750
    }
16751
16752
#ifndef NO_DES3
16753
16754
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
16755
                            unsigned char* iv, int len)
16756
{
16757
    (void)len;
16758
16759
    WOLFSSL_MSG("wolfSSL_3des_iv");
16760
16761
    if (ctx == NULL || iv == NULL) {
16762
        WOLFSSL_MSG("Bad function argument");
16763
        return;
16764
    }
16765
16766
    if (doset)
16767
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
16768
    else
16769
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
16770
}
16771
16772
#endif /* NO_DES3 */
16773
16774
16775
#ifndef NO_AES
16776
16777
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
16778
                      unsigned char* iv, int len)
16779
{
16780
    (void)len;
16781
16782
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
16783
16784
    if (ctx == NULL || iv == NULL) {
16785
        WOLFSSL_MSG("Bad function argument");
16786
        return;
16787
    }
16788
16789
    if (doset)
16790
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
16791
    else
16792
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
16793
}
16794
16795
#endif /* NO_AES */
16796
16797
#endif /* OPENSSL_EXTRA */
16798
16799
/*******************************************************************************
16800
 * END OF EVP_CIPHER API
16801
 ******************************************************************************/
16802
16803
#ifndef NO_CERTS
16804
16805
#define WOLFSSL_X509_STORE_INCLUDED
16806
#include <src/x509_str.c>
16807
16808
#define WOLFSSL_SSL_P7P12_INCLUDED
16809
#include <src/ssl_p7p12.c>
16810
16811
#endif /* !NO_CERTS */
16812
16813
16814
/*******************************************************************************
16815
 * BEGIN OPENSSL FIPS DRBG APIs
16816
 ******************************************************************************/
16817
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
16818
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
16819
{
16820
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16821
    if (ctx != NULL) {
16822
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
16823
        ctx->type = type;
16824
        ctx->xflags = (int)flags;
16825
        ctx->status = DRBG_STATUS_UNINITIALISED;
16826
        ret = WOLFSSL_SUCCESS;
16827
    }
16828
    return ret;
16829
}
16830
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
16831
{
16832
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16833
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
16834
        NULL, DYNAMIC_TYPE_OPENSSL);
16835
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
16836
    if (ret == WOLFSSL_SUCCESS && type != 0) {
16837
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
16838
    }
16839
    if (ret != WOLFSSL_SUCCESS) {
16840
        WOLFSSL_ERROR(ret);
16841
        wolfSSL_FIPS_drbg_free(ctx);
16842
        ctx = NULL;
16843
    }
16844
    return ctx;
16845
}
16846
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
16847
    const unsigned char* pers, size_t perslen)
16848
{
16849
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16850
    if (ctx != NULL && ctx->rng == NULL) {
16851
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16852
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
16853
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
16854
    #else
16855
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
16856
        if (ctx->rng != NULL) {
16857
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
16858
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
16859
        #else
16860
            ret = wc_InitRng(ctx->rng);
16861
            (void)pers;
16862
            (void)perslen;
16863
        #endif
16864
            if (ret != 0) {
16865
                WOLFSSL_ERROR(ret);
16866
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
16867
                ctx->rng = NULL;
16868
            }
16869
        }
16870
    #endif
16871
    }
16872
    if (ctx != NULL && ctx->rng != NULL) {
16873
        ctx->status = DRBG_STATUS_READY;
16874
        ret = WOLFSSL_SUCCESS;
16875
    }
16876
    return ret;
16877
}
16878
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
16879
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
16880
    size_t entropy_blocklen,
16881
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
16882
{
16883
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16884
    if (ctx != NULL) {
16885
        ctx->entropy_get = entropy_get;
16886
        ctx->entropy_clean = entropy_clean;
16887
        ctx->entropy_blocklen = entropy_blocklen;
16888
        ctx->none_get = none_get;
16889
        ctx->nonce_clean = nonce_clean;
16890
        ret = WOLFSSL_SUCCESS;
16891
    }
16892
    return ret;
16893
}
16894
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
16895
{
16896
    /* not implemented */
16897
    (void)buf;
16898
    (void)num;
16899
    (void)entropy;
16900
}
16901
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
16902
    size_t adinlen)
16903
{
16904
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16905
    if (ctx != NULL && ctx->rng != NULL) {
16906
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16907
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
16908
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
16909
            ret = WOLFSSL_SUCCESS;
16910
        }
16911
    #else
16912
        ret = WOLFSSL_SUCCESS;
16913
        (void)adin;
16914
        (void)adinlen;
16915
    #endif
16916
    }
16917
    return ret;
16918
}
16919
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
16920
    size_t outlen, int prediction_resistance, const unsigned char* adin,
16921
    size_t adinlen)
16922
{
16923
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16924
    if (ctx != NULL && ctx->rng != NULL) {
16925
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
16926
        if (ret == 0) {
16927
            ret = WOLFSSL_SUCCESS;
16928
        }
16929
    }
16930
    (void)prediction_resistance;
16931
    (void)adin;
16932
    (void)adinlen;
16933
    return ret;
16934
}
16935
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
16936
{
16937
    if (ctx != NULL && ctx->rng != NULL) {
16938
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
16939
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
16940
        wc_rng_free(ctx->rng);
16941
    #else
16942
        wc_FreeRng(ctx->rng);
16943
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
16944
    #endif
16945
        ctx->rng = NULL;
16946
        ctx->status = DRBG_STATUS_UNINITIALISED;
16947
    }
16948
    return WOLFSSL_SUCCESS;
16949
}
16950
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
16951
{
16952
    if (ctx != NULL) {
16953
        /* As safety check if free'ing the default drbg, then mark global NULL.
16954
         * Technically the user should not call free on the default drbg. */
16955
        if (ctx == gDrbgDefCtx) {
16956
            gDrbgDefCtx = NULL;
16957
        }
16958
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
16959
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
16960
    }
16961
}
16962
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
16963
{
16964
    if (gDrbgDefCtx == NULL) {
16965
        gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
16966
    }
16967
    return gDrbgDefCtx;
16968
}
16969
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
16970
{
16971
    /* not implemented */
16972
    (void)buf;
16973
    (void)pctr;
16974
}
16975
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
16976
{
16977
    if (ctx != NULL) {
16978
        return ctx->app_data;
16979
    }
16980
    return NULL;
16981
}
16982
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
16983
{
16984
    if (ctx != NULL) {
16985
        ctx->app_data = app_data;
16986
    }
16987
}
16988
#endif
16989
/*******************************************************************************
16990
 * END OF OPENSSL FIPS DRBG APIs
16991
 ******************************************************************************/
16992
16993
16994
#endif /* !WOLFCRYPT_ONLY */