Coverage Report

Created: 2026-04-05 07:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-sp-math-all/src/ssl.c
Line
Count
Source
1
/* ssl.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE)
25
    /* turn on GNU extensions for XISASCII */
26
    #define _GNU_SOURCE 1
27
#endif
28
29
#if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \
30
    defined(OPENSSL_EXTRA_X509_SMALL)
31
32
#include <wolfssl/internal.h>
33
#include <wolfssl/error-ssl.h>
34
#include <wolfssl/wolfcrypt/error-crypt.h>
35
#include <wolfssl/wolfcrypt/coding.h>
36
#include <wolfssl/wolfcrypt/kdf.h>
37
#ifdef NO_INLINE
38
    #include <wolfssl/wolfcrypt/misc.h>
39
#else
40
    #define WOLFSSL_MISC_INCLUDED
41
    #include <wolfcrypt/src/misc.c>
42
#endif
43
44
#ifdef HAVE_ERRNO_H
45
    #include <errno.h>
46
#endif
47
48
49
#if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
50
    #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
51
                && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
52
                && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
53
        #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(HAVE_DILITHIUM)
119
        #include <wolfssl/wolfcrypt/dilithium.h>
120
    #endif /* HAVE_DILITHIUM */
121
    #if defined(HAVE_SPHINCS)
122
        #include <wolfssl/wolfcrypt/sphincs.h>
123
    #endif /* HAVE_SPHINCS */
124
    #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
125
        #ifdef HAVE_OCSP
126
            #include <wolfssl/openssl/ocsp.h>
127
        #endif
128
        #include <wolfssl/openssl/lhash.h>
129
        #include <wolfssl/openssl/txt_db.h>
130
    #endif /* WITH_STUNNEL */
131
    #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
132
        #include <wolfssl/wolfcrypt/sha512.h>
133
    #endif
134
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
135
        && !defined(WC_NO_RNG)
136
        #include <wolfssl/wolfcrypt/srp.h>
137
    #endif
138
#endif
139
140
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
141
    #include <wolfssl/openssl/x509v3.h>
142
    int wolfssl_bn_get_value(WOLFSSL_BIGNUM* bn, mp_int* mpi);
143
    int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi);
144
#endif
145
146
#if defined(WOLFSSL_QT)
147
    #include <wolfssl/wolfcrypt/sha.h>
148
#endif
149
150
#ifdef NO_ASN
151
    #include <wolfssl/wolfcrypt/dh.h>
152
#endif
153
#endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
154
155
/*
156
 * ssl.c Build Options:
157
 *
158
 * See also: tls.c for TLS extension/protocol options, tls13.c for TLS 1.3,
159
 *           internal.c for handshake internals, wc_port.c for platform/memory.
160
 *
161
 * OpenSSL Compatibility:
162
 * OPENSSL_EXTRA:              Enable OpenSSL compatibility API        default: off
163
 * OPENSSL_ALL:                Enable all OpenSSL compat APIs          default: off
164
 * OPENSSL_EXTRA_X509_SMALL:   Minimal OpenSSL X509 compat APIs       default: off
165
 * OPENSSL_EXTRA_NO_ASN1:      OpenSSL extra without ASN1 objects      default: off
166
 * OPENSSL_COMPATIBLE_DEFAULTS:
167
 *                  Default behavior compatible with OpenSSL           default: off
168
 * NO_WOLFSSL_STUB:            Disable stubs for unimplemented funcs   default: off
169
 * WOLFSSL_DEBUG_OPENSSL:      Debug logging for OpenSSL compat layer  default: off
170
 * WOLFSSL_HAVE_ERROR_QUEUE:   OpenSSL-compatible error queue          default: off
171
 * WOLFSSL_ERROR_CODE_OPENSSL: Use OpenSSL-compatible error codes      default: off
172
 * WOLFSSL_CIPHER_INTERNALNAME:
173
 *                  Use wolfSSL internal cipher suite names             default: off
174
 * NO_CIPHER_SUITE_ALIASES:    Disable cipher suite name aliases       default: off
175
 * WOLFSSL_SET_CIPHER_BYTES:   Set cipher suites by raw byte values    default: off
176
 * WOLFSSL_OLD_SET_CURVES_LIST:
177
 *                  Old-style curve list parsing for compat             default: off
178
 * WOLFSSL_NO_OPENSSL_RAND_CB: Disable OpenSSL RAND callback compat   default: off
179
 * NO_ERROR_STRINGS:           Disable human-readable error strings    default: off
180
 * WOLFSSL_PUBLIC_ASN:         Make ASN parsing functions public        default: off
181
 *
182
 * Extra Data / BIO:
183
 * HAVE_EX_DATA:               Enable ex_data on SSL/CTX/X509 objects  default: off
184
 * HAVE_EX_DATA_CLEANUP_HOOKS: Cleanup callbacks for ex_data           default: off
185
 * HAVE_EX_DATA_CRYPTO:        ex_data support for wolfCrypt objects   default: off
186
 * MAX_EX_DATA:                Max ex_data entries per object           default: 5
187
 * NO_BIO:                     Disable BIO abstraction layer           default: off
188
 *
189
 * Session & Cache:
190
 * NO_SESSION_CACHE:           Disable server session cache            default: off
191
 * NO_SESSION_CACHE_REF:       wolfSSL_get_session returns ssl->session
192
 *                             reference instead of ClientCache ref    default: off
193
 * SESSION_CACHE_DYNAMIC_MEM:  Dynamically allocate session cache      default: off
194
 * NO_CLIENT_CACHE:            Disable client-side session cache       default: off
195
 * SESSION_CERTS:              Store full cert chain in session         default: off
196
 * WOLFSSL_SESSION_ID_CTX:     Session ID context for cache sharing    default: off
197
 *
198
 * I/O & Transport:
199
 * USE_WOLFSSL_IO:             Use built-in I/O callbacks              default: on
200
 * WOLFSSL_USER_IO:            Application provides custom I/O         default: off
201
 * WOLFSSL_NO_SOCK:            Build without socket support            default: off
202
 * NO_WRITEV:                  Disable writev() scatter/gather I/O     default: off
203
 * WOLFSSL_DTLS_MTU:           Enable DTLS MTU management APIs         default: off
204
 * WOLFSSL_DTLS_DROP_STATS:    Track DTLS packet drop statistics       default: off
205
 * WOLFSSL_MULTICAST:          Enable DTLS multicast support           default: off
206
 *
207
 * Callbacks & Features:
208
 * WOLFSSL_CHECK_ALERT_ON_ERR: Check alerts on handshake error         default: off
209
 * ATOMIC_USER:                User-defined record layer callbacks      default: off
210
 * HAVE_WRITE_DUP:             Separate threads for SSL read/write     default: off
211
 * WOLFSSL_CALLBACKS:          Handshake monitoring callbacks           default: off
212
 * NO_HANDSHAKE_DONE_CB:       Disable handshake completion callback   default: off
213
 * WOLFSSL_SHUTDOWNONCE:       Send close_notify only once             default: off
214
 * WOLFSSL_COPY_CERT:          Copy certificate buffer (own copy)      default: off
215
 * WOLFSSL_COPY_KEY:           Copy private key buffer (own copy)      default: off
216
 * WOLF_PRIVATE_KEY_ID:        Reference private keys by ID            default: off
217
 * WOLFSSL_REFCNT_ERROR_RETURN:
218
 *                  Return errors on ref counting failures             default: off
219
 * WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST:
220
 *                  Allow runtime max fragment size adjustment          default: off
221
 * WOLFSSL_ALLOW_NO_SUITES:    Allow SSL objects with no cipher suites default: off
222
 *
223
 * Certificates & Keys:
224
 * KEEP_PEER_CERT:             Keep peer cert after handshake          default: off
225
 * KEEP_OUR_CERT:              Keep our cert after handshake           default: off
226
 * WOLFSSL_STATIC_RSA:         Enable static RSA key exchange          default: off
227
 * WOLFSSL_HAVE_CERT_SERVICE:  Certificate service callbacks           default: off
228
 * WOLFSSL_SYS_CA_CERTS:       Load system CA certs from OS            default: off
229
 *
230
 * Application Compatibility:
231
 * HAVE_CURL:                  APIs for libcurl compatibility          default: off
232
 * HAVE_LIGHTY:                APIs for lighttpd compatibility         default: off
233
 * HAVE_MEMCACHED:             APIs for memcached compatibility        default: off
234
 * WOLFSSL_APACHE_HTTPD:       APIs for Apache httpd compatibility     default: off
235
 * WOLFSSL_NGINX:              APIs for nginx compatibility            default: off
236
 * WOLFSSL_HAPROXY:            APIs for HAProxy compatibility          default: off
237
 * WOLFSSL_ASIO:               APIs for Boost.Asio compatibility       default: off
238
 * WOLFSSL_PYTHON:             APIs for Python module compatibility    default: off
239
 * WOLFSSL_QT:                 APIs for Qt framework compatibility     default: off
240
 * WOLFSSL_JNI:                APIs for Java JNI/JSSE compatibility    default: off
241
 *
242
 * Protocol Features:
243
 * WOLFSSL_HAVE_WOLFSCEP:      Enable wolfSCEP protocol support        default: off
244
 * WOLFCRYPT_HAVE_SRP:         Enable SRP protocol support             default: off
245
 * HAVE_LIBZ:                  Enable zlib TLS compression             default: off
246
 * WOLFSSL_EXTRA:              Extra SSL session info APIs              default: off
247
 * WOLFSSL_WPAS_SMALL:         Minimal wpa_supplicant/hostapd APIs     default: off
248
 * HAVE_FUZZER:                Fuzzing callback support                 default: off
249
 *
250
 * Memory & Threading:
251
 * WOLFSSL_STATIC_MEMORY_LEAN: Lean static memory allocation           default: off
252
 * WOLFSSL_THREADED_CRYPT:     Multi-threaded crypto operations         default: off
253
 * WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS:
254
 *                  Thread-safe cleanup via atomics                     default: off
255
 * WOLFSSL_ATOMIC_INITIALIZER: Static init for atomic variables        default: off
256
 * WOLFSSL_DEBUG_MEMORY:       Log malloc/free with file/line info     default: off
257
 * WOLFSSL_NO_REALLOC:         Disable realloc, use malloc+copy+free   default: off
258
 * WOLFSSL_HEAP_TEST:          Heap-related testing utilities           default: off
259
 *
260
 * Debugging & Build:
261
 * SHOW_SIZES:                 Display struct sizes at init             default: off
262
 * WOLFSSL_DEBUG_TRACE_ERROR_CODES:
263
 *                  Trace error code origins for debugging              default: off
264
 * HAVE_ATEXIT:                Register wolfSSL_Cleanup via atexit     default: off
265
 * WOLFSSL_SYS_CRYPTO_POLICY:  Honor system crypto policy settings     default: off
266
 *
267
 * Hardware TLS:
268
 * WOLFSSL_RENESAS_TSIP_TLS:   Renesas TSIP hardware crypto for TLS   default: off
269
 * WOLFSSL_RENESAS_FSPSM_TLS:  Renesas FSP Security Module for TLS    default: off
270
 * WOLFSSL_EGD_NBLOCK:         Non-blocking EGD entropy support        default: off
271
 */
272
273
#define WOLFSSL_SSL_MISC_INCLUDED
274
#include "src/ssl_misc.c"
275
276
#define WOLFSSL_EVP_INCLUDED
277
#include "wolfcrypt/src/evp.c"
278
279
/* Crypto code uses EVP APIs. */
280
#define WOLFSSL_SSL_CRYPTO_INCLUDED
281
#include "src/ssl_crypto.c"
282
283
#ifndef WOLFCRYPT_ONLY
284
#define WOLFSSL_SSL_CERTMAN_INCLUDED
285
#include "src/ssl_certman.c"
286
287
#define WOLFSSL_SSL_SESS_INCLUDED
288
#include "src/ssl_sess.c"
289
290
#define WOLFSSL_SSL_API_CERT_INCLUDED
291
#include "src/ssl_api_cert.c"
292
293
#define WOLFSSL_SSL_API_PK_INCLUDED
294
#include "src/ssl_api_pk.c"
295
#endif
296
297
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
298
    !defined(WOLFCRYPT_ONLY)
299
/* Convert shortname to NID.
300
 *
301
 * For OpenSSL compatibility.
302
 *
303
 * @param [in] sn  Short name of OID.
304
 * @return  NID corresponding to shortname on success.
305
 * @return  WC_NID_undef when not recognized.
306
 */
307
int wc_OBJ_sn2nid(const char *sn)
308
{
309
    const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
310
    size_t i;
311
    WOLFSSL_ENTER("wc_OBJ_sn2nid");
312
    for (i = 0; i < wolfssl_object_info_sz; i++, obj_info++) {
313
        if (XSTRCMP(sn, obj_info->sName) == 0)
314
            return obj_info->nid;
315
    }
316
    WOLFSSL_MSG("short name not found in table");
317
    return WC_NID_undef;
318
}
319
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
320
321
#ifndef WOLFCRYPT_ONLY
322
323
324
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
325
/* The system wide crypto-policy. Configured by wolfSSL_crypto_policy_enable.
326
 * */
327
static struct SystemCryptoPolicy crypto_policy;
328
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
329
330
#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \
331
    (defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && !defined(NO_DSA))
332
333
#define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
334
static WC_RNG globalRNG;
335
static volatile int initGlobalRNG = 0;
336
337
#if defined(OPENSSL_EXTRA) || !defined(WOLFSSL_MUTEX_INITIALIZER)
338
static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex
339
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex);
340
#endif
341
#ifndef WOLFSSL_MUTEX_INITIALIZER
342
static int globalRNGMutex_valid = 0;
343
#endif
344
345
#if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
346
static WOLFSSL_DRBG_CTX* gDrbgDefCtx = NULL;
347
#endif
348
349
WC_RNG* wolfssl_get_global_rng(void)
350
713
{
351
713
    WC_RNG* ret = NULL;
352
353
713
    if (initGlobalRNG == 0)
354
694
        WOLFSSL_MSG("Global RNG no Init");
355
19
    else
356
19
        ret = &globalRNG;
357
358
713
    return ret;
359
713
}
360
361
/* Make a global RNG and return.
362
 *
363
 * @return  Global RNG on success.
364
 * @return  NULL on error.
365
 */
366
WC_RNG* wolfssl_make_global_rng(void)
367
0
{
368
0
    WC_RNG* ret;
369
370
0
#ifdef HAVE_GLOBAL_RNG
371
    /* Get the global random number generator instead. */
372
0
    ret = wolfssl_get_global_rng();
373
#ifdef OPENSSL_EXTRA
374
    if (ret == NULL) {
375
        /* Create a global random if possible. */
376
        (void)wolfSSL_RAND_Init();
377
        ret = wolfssl_get_global_rng();
378
    }
379
#endif
380
#else
381
    WOLFSSL_ERROR_MSG("Bad RNG Init");
382
    ret = NULL;
383
#endif
384
385
0
    return ret;
386
0
}
387
388
/* Too many defines to check explicitly - prototype it and always include
389
 * for RSA, DH, ECC and DSA for BN. */
390
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local);
391
392
/* Make a random number generator or get global if possible.
393
 *
394
 * Global may not be available and NULL will be returned.
395
 *
396
 * @param [in, out] rng    Local random number generator.
397
 * @param [out]     local  Local random number generator returned.
398
 * @return  NULL on failure.
399
 * @return  A random number generator object.
400
 */
401
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local)
402
879
{
403
879
    WC_RNG* ret = NULL;
404
879
#ifdef WOLFSSL_SMALL_STACK
405
879
    int freeRng = 0;
406
407
    /* Allocate RNG object . */
408
879
    if (rng == NULL) {
409
879
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
410
879
        freeRng = 1;
411
879
    }
412
879
#endif
413
414
879
    if (rng != NULL) {
415
879
        if (wc_InitRng(rng) == 0) {
416
879
            ret = rng;
417
879
            *local = 1;
418
879
        }
419
0
        else {
420
0
            WOLFSSL_MSG("Bad RNG Init");
421
0
#ifdef WOLFSSL_SMALL_STACK
422
0
            if (freeRng) {
423
0
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
424
0
                rng = NULL;
425
0
            }
426
0
#endif
427
0
        }
428
879
    }
429
879
    if (ret == NULL) {
430
0
#ifdef HAVE_GLOBAL_RNG
431
0
        WOLFSSL_MSG("trying global RNG");
432
0
#endif
433
0
        ret = wolfssl_make_global_rng();
434
0
    }
435
436
879
    return ret;
437
879
}
438
#endif
439
440
#ifdef OPENSSL_EXTRA
441
    /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
442
     *                OPENSSL_EXTRA where RAND callbacks are not used */
443
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
444
        static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
445
        static wolfSSL_Mutex gRandMethodMutex
446
            WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex);
447
        #ifndef WOLFSSL_MUTEX_INITIALIZER
448
        static int gRandMethodsInit = 0;
449
        #endif
450
    #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
451
#endif /* OPENSSL_EXTRA */
452
453
#define WOLFSSL_SSL_BN_INCLUDED
454
#include "src/ssl_bn.c"
455
456
#ifndef OPENSSL_EXTRA_NO_ASN1
457
#define WOLFSSL_SSL_ASN1_INCLUDED
458
#include "src/ssl_asn1.c"
459
#endif /* OPENSSL_EXTRA_NO_ASN1 */
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.23k
{
549
5.23k
    WOLFSSL_CTX* ctx = NULL;
550
551
5.23k
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
552
553
5.23k
    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.23k
#ifndef NO_TLS
565
5.23k
    if (method == NULL)
566
0
        return ctx;
567
#else
568
    /* a blank TLS method */
569
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
570
#endif
571
572
5.23k
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
573
5.23k
    if (ctx) {
574
5.23k
        int ret;
575
576
5.23k
        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.23k
        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.23k
    }
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.23k
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
648
5.23k
    return ctx;
649
5.23k
}
650
651
652
WOLFSSL_ABI
653
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
654
5.28k
{
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.28k
    return wolfSSL_CTX_new_ex(method, NULL);
660
5.28k
#endif
661
5.28k
}
662
663
/* increases CTX reference count to track proper time to "free" */
664
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
665
91.2k
{
666
91.2k
    int ret;
667
91.2k
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
668
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
669
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
670
#else
671
91.2k
    (void)ret;
672
91.2k
    return WOLFSSL_SUCCESS;
673
91.2k
#endif
674
91.2k
}
675
676
WOLFSSL_ABI
677
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
678
5.23k
{
679
5.23k
    WOLFSSL_ENTER("wolfSSL_CTX_free");
680
5.23k
    if (ctx) {
681
5.23k
        FreeSSL_Ctx(ctx);
682
5.23k
    }
683
684
5.23k
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
685
5.23k
}
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
16
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
768
16
                        (int)sizeof(WOLFSSL));
769
16
    }
770
91.5k
    else {
771
91.5k
        ret = InitSSL(ssl, ctx, 0);
772
91.5k
        if (ret < 0) {
773
6.35k
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
774
6.35k
            FreeSSL(ssl, ctx->heap);
775
6.35k
            ssl = NULL;
776
6.35k
        }
777
85.1k
        else if (ret == 0) {
778
85.1k
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
779
85.1k
        }
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
85.2k
{
797
85.2k
    WOLFSSL_ENTER("wolfSSL_free");
798
799
85.2k
    if (ssl) {
800
85.1k
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
801
85.1k
        FreeSSL(ssl, ssl->ctx->heap);
802
85.1k
    }
803
128
    else {
804
128
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
805
128
    }
806
85.2k
    WOLFSSL_LEAVE("wolfSSL_free", 0);
807
85.2k
}
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
        WOLFSSL_MSG("Did WriteDup full free, count to zero");
867
    }
868
}
869
870
871
/*
872
 * duplicate existing ssl members into dup needed for writing
873
 *
874
 * dup write only WOLFSSL
875
 * ssl existing WOLFSSL
876
 *
877
 * 0 on success
878
*/
879
static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
880
{
881
    word16 tmp_weOwnRng;
882
883
    /* shared dupWrite setup */
884
    ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
885
                                       DYNAMIC_TYPE_WRITEDUP);
886
    if (ssl->dupWrite == NULL) {
887
        return MEMORY_E;
888
    }
889
    XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
890
891
    if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
892
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
893
        ssl->dupWrite = NULL;
894
        return BAD_MUTEX_E;
895
    }
896
    ssl->dupWrite->dupCount = 2;    /* both sides have a count to start */
897
    dup->dupWrite = ssl->dupWrite; /* each side uses */
898
899
    tmp_weOwnRng = dup->options.weOwnRng;
900
901
    /* copy write parts over to dup writer */
902
    XMEMCPY(&dup->specs,   &ssl->specs,   sizeof(CipherSpecs));
903
    XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
904
    XMEMCPY(&dup->keys,    &ssl->keys,    sizeof(Keys));
905
    XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
906
    XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
907
    XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
908
909
    /* dup side now owns encrypt/write ciphers */
910
    XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
911
912
#ifdef HAVE_ONE_TIME_AUTH
913
#ifdef HAVE_POLY1305
914
    if (ssl->auth.setup && ssl->auth.poly1305 != NULL) {
915
        dup->auth.poly1305 = (Poly1305*)XMALLOC(sizeof(Poly1305), dup->heap,
916
            DYNAMIC_TYPE_CIPHER);
917
        if (dup->auth.poly1305 == NULL)
918
            return MEMORY_E;
919
        dup->auth.setup = 1;
920
    }
921
#endif
922
#endif
923
924
#ifdef WOLFSSL_TLS13
925
    if (IsAtLeastTLSv1_3(ssl->version)) {
926
        /* Copy TLS 1.3 application traffic secrets so the write side can
927
         * derive updated keys when wolfSSL_update_keys() is called. */
928
        XMEMCPY(dup->clientSecret, ssl->clientSecret, SECRET_LEN);
929
        XMEMCPY(dup->serverSecret, ssl->serverSecret, SECRET_LEN);
930
931
#ifdef WOLFSSL_DTLS13
932
        if (ssl->options.dtls) {
933
            /* Copy epoch array (contains only value types -- safe to memcpy). */
934
            XMEMCPY(dup->dtls13Epochs, ssl->dtls13Epochs,
935
                    sizeof(ssl->dtls13Epochs));
936
937
            /* Re-point dtls13EncryptEpoch into dup's own epoch array. */
938
            if (ssl->dtls13EncryptEpoch != NULL) {
939
                dup->dtls13EncryptEpoch =
940
                    &dup->dtls13Epochs[ssl->dtls13EncryptEpoch -
941
                                       ssl->dtls13Epochs];
942
            }
943
944
            /* Copy current write epoch number. */
945
            dup->dtls13Epoch = ssl->dtls13Epoch;
946
947
            /* Transfer record-number encryption cipher ownership to dup. */
948
            XMEMCPY(&dup->dtlsRecordNumberEncrypt,
949
                    &ssl->dtlsRecordNumberEncrypt, sizeof(RecordNumberCiphers));
950
            XMEMSET(&ssl->dtlsRecordNumberEncrypt,
951
                    0, sizeof(RecordNumberCiphers));
952
        }
953
#endif /* WOLFSSL_DTLS13 */
954
    }
955
#endif /* WOLFSSL_TLS13 */
956
957
958
    dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
959
    dup->CBIOSend = ssl->CBIOSend;
960
#ifdef OPENSSL_EXTRA
961
    dup->cbioFlag = ssl->cbioFlag;
962
#endif
963
    dup->wfd    = ssl->wfd;
964
    dup->wflags = ssl->wflags;
965
#ifndef WOLFSSL_AEAD_ONLY
966
    dup->hmac   = ssl->hmac;
967
#endif
968
#ifdef HAVE_TRUNCATED_HMAC
969
    dup->truncated_hmac = ssl->truncated_hmac;
970
#endif
971
972
    /* Restore rng option */
973
    dup->options.weOwnRng = tmp_weOwnRng;
974
975
    /* unique side dup setup */
976
    dup->dupSide = WRITE_DUP_SIDE;
977
    ssl->dupSide = READ_DUP_SIDE;
978
979
    return 0;
980
}
981
982
983
/*
984
 * duplicate a WOLFSSL object post handshake for writing only
985
 * turn existing object into read only.  Allows concurrent access from two
986
 * different threads.
987
 *
988
 * ssl existing WOLFSSL object
989
 *
990
 * return dup'd WOLFSSL object on success
991
*/
992
WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
993
{
994
    WOLFSSL* dup = NULL;
995
    int ret = 0;
996
997
    (void)ret;
998
    WOLFSSL_ENTER("wolfSSL_write_dup");
999
1000
    if (ssl == NULL) {
1001
        return ssl;
1002
    }
1003
1004
    if (ssl->options.handShakeDone == 0) {
1005
        WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
1006
        return NULL;
1007
    }
1008
1009
    if (ssl->dupWrite) {
1010
        WOLFSSL_MSG("wolfSSL_write_dup already called once");
1011
        return NULL;
1012
    }
1013
1014
    dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
1015
    if (dup) {
1016
        if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
1017
            FreeSSL(dup, ssl->ctx->heap);
1018
            dup = NULL;
1019
        } else if ( (ret = DupSSL(dup, ssl)) < 0) {
1020
            FreeSSL(dup, ssl->ctx->heap);
1021
            dup = NULL;
1022
        }
1023
    }
1024
1025
    WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
1026
1027
    return dup;
1028
}
1029
1030
1031
/*
1032
 * Notify write dup side of fatal error or close notify
1033
 *
1034
 * ssl WOLFSSL object
1035
 * err Notify err
1036
 *
1037
 * 0 on success
1038
*/
1039
int NotifyWriteSide(WOLFSSL* ssl, int err)
1040
{
1041
    int ret;
1042
1043
    WOLFSSL_ENTER("NotifyWriteSide");
1044
1045
    ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
1046
    if (ret == 0) {
1047
        ssl->dupWrite->dupErr = err;
1048
        ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1049
    }
1050
1051
    return ret;
1052
}
1053
1054
1055
#endif /* HAVE_WRITE_DUP */
1056
1057
1058
#ifdef HAVE_POLY1305
1059
/* set if to use old poly 1 for yes 0 to use new poly */
1060
int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
1061
0
{
1062
0
    (void)ssl;
1063
0
    (void)value;
1064
1065
0
#ifndef WOLFSSL_NO_TLS12
1066
0
    WOLFSSL_ENTER("wolfSSL_use_old_poly");
1067
0
    WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
1068
0
            "is depreciated");
1069
0
    ssl->options.oldPoly = (word16)value;
1070
0
    WOLFSSL_LEAVE("wolfSSL_use_old_poly", 0);
1071
0
#endif
1072
0
    return 0;
1073
0
}
1074
#endif
1075
1076
1077
WOLFSSL_ABI
1078
int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
1079
0
{
1080
0
    int ret;
1081
1082
0
    WOLFSSL_ENTER("wolfSSL_set_fd");
1083
1084
0
    if (ssl == NULL) {
1085
0
        return BAD_FUNC_ARG;
1086
0
    }
1087
1088
0
    ret = wolfSSL_set_read_fd(ssl, fd);
1089
0
    if (ret == WOLFSSL_SUCCESS) {
1090
0
        ret = wolfSSL_set_write_fd(ssl, fd);
1091
0
    }
1092
1093
0
    return ret;
1094
0
}
1095
1096
#ifdef WOLFSSL_DTLS
1097
int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd)
1098
{
1099
    int ret;
1100
1101
    WOLFSSL_ENTER("wolfSSL_set_dtls_fd_connected");
1102
1103
    if (ssl == NULL) {
1104
        return BAD_FUNC_ARG;
1105
    }
1106
1107
    ret = wolfSSL_set_fd(ssl, fd);
1108
    if (ret == WOLFSSL_SUCCESS)
1109
        ssl->buffers.dtlsCtx.connected = 1;
1110
1111
    return ret;
1112
}
1113
#endif
1114
1115
1116
int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
1117
0
{
1118
0
    WOLFSSL_ENTER("wolfSSL_set_read_fd");
1119
1120
0
    if (ssl == NULL) {
1121
0
        return BAD_FUNC_ARG;
1122
0
    }
1123
1124
0
    ssl->rfd = fd;      /* not used directly to allow IO callbacks */
1125
0
    ssl->IOCB_ReadCtx  = &ssl->rfd;
1126
1127
    #ifdef WOLFSSL_DTLS
1128
        ssl->buffers.dtlsCtx.connected = 0;
1129
        if (ssl->options.dtls) {
1130
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
1131
            ssl->buffers.dtlsCtx.rfd = fd;
1132
        }
1133
    #endif
1134
1135
0
    WOLFSSL_LEAVE("wolfSSL_set_read_fd", WOLFSSL_SUCCESS);
1136
0
    return WOLFSSL_SUCCESS;
1137
0
}
1138
1139
1140
int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
1141
0
{
1142
0
    WOLFSSL_ENTER("wolfSSL_set_write_fd");
1143
1144
0
    if (ssl == NULL) {
1145
0
        return BAD_FUNC_ARG;
1146
0
    }
1147
1148
0
    ssl->wfd = fd;      /* not used directly to allow IO callbacks */
1149
0
    ssl->IOCB_WriteCtx  = &ssl->wfd;
1150
1151
    #ifdef WOLFSSL_DTLS
1152
        ssl->buffers.dtlsCtx.connected = 0;
1153
        if (ssl->options.dtls) {
1154
            ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
1155
            ssl->buffers.dtlsCtx.wfd = fd;
1156
        }
1157
    #endif
1158
1159
0
    WOLFSSL_LEAVE("wolfSSL_set_write_fd", WOLFSSL_SUCCESS);
1160
0
    return WOLFSSL_SUCCESS;
1161
0
}
1162
1163
1164
/**
1165
  * Get the name of cipher at priority level passed in.
1166
  */
1167
char* wolfSSL_get_cipher_list(int priority)
1168
0
{
1169
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1170
1171
0
    if (priority >= GetCipherNamesSize() || priority < 0) {
1172
0
        return 0;
1173
0
    }
1174
1175
0
    return (char*)ciphers[priority].name;
1176
0
}
1177
1178
1179
/**
1180
  * Get the name of cipher at priority level passed in.
1181
  */
1182
char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
1183
0
{
1184
1185
0
    if (ssl == NULL) {
1186
0
        return NULL;
1187
0
    }
1188
0
    else {
1189
0
        const char* cipher;
1190
1191
0
        if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
1192
0
            if (priority == 0) {
1193
0
                return (char*)cipher;
1194
0
            }
1195
0
            else {
1196
0
                return NULL;
1197
0
            }
1198
0
        }
1199
0
        else {
1200
0
            return wolfSSL_get_cipher_list(priority);
1201
0
        }
1202
0
    }
1203
0
}
1204
1205
1206
int wolfSSL_get_ciphers(char* buf, int len)
1207
0
{
1208
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1209
0
    int ciphersSz = GetCipherNamesSize();
1210
0
    int i;
1211
1212
0
    if (buf == NULL || len <= 0)
1213
0
        return BAD_FUNC_ARG;
1214
1215
    /* Add each member to the buffer delimited by a : */
1216
0
    for (i = 0; i < ciphersSz; i++) {
1217
0
        int cipherNameSz = (int)XSTRLEN(ciphers[i].name);
1218
0
        if (cipherNameSz + 1 < len) {
1219
0
            XSTRNCPY(buf, ciphers[i].name, (size_t)len);
1220
0
            buf += cipherNameSz;
1221
1222
0
            if (i < ciphersSz - 1)
1223
0
                *buf++ = ':';
1224
0
            *buf = 0;
1225
1226
0
            len -= cipherNameSz + 1;
1227
0
        }
1228
0
        else
1229
0
            return BUFFER_E;
1230
0
    }
1231
0
    return WOLFSSL_SUCCESS;
1232
0
}
1233
1234
1235
#ifndef NO_ERROR_STRINGS
1236
/* places a list of all supported cipher suites in TLS_* format into "buf"
1237
 * return WOLFSSL_SUCCESS on success */
1238
int wolfSSL_get_ciphers_iana(char* buf, int len)
1239
0
{
1240
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1241
0
    int ciphersSz = GetCipherNamesSize();
1242
0
    int i;
1243
0
    int cipherNameSz;
1244
1245
0
    if (buf == NULL || len <= 0)
1246
0
        return BAD_FUNC_ARG;
1247
1248
    /* Add each member to the buffer delimited by a : */
1249
0
    for (i = 0; i < ciphersSz; i++) {
1250
0
#ifndef NO_CIPHER_SUITE_ALIASES
1251
0
        if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
1252
0
            continue;
1253
0
#endif
1254
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
1255
0
        if (cipherNameSz + 1 < len) {
1256
0
            XSTRNCPY(buf, ciphers[i].name_iana, (size_t)len);
1257
0
            buf += cipherNameSz;
1258
1259
0
            if (i < ciphersSz - 1)
1260
0
                *buf++ = ':';
1261
0
            *buf = 0;
1262
1263
0
            len -= cipherNameSz + 1;
1264
0
        }
1265
0
        else
1266
0
            return BUFFER_E;
1267
0
    }
1268
0
    return WOLFSSL_SUCCESS;
1269
0
}
1270
#endif /* NO_ERROR_STRINGS */
1271
1272
1273
const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
1274
0
{
1275
0
    const char* cipher;
1276
1277
0
    if (ssl == NULL || len <= 0)
1278
0
        return NULL;
1279
1280
0
    cipher = wolfSSL_get_cipher_name_iana(ssl);
1281
0
    len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1));
1282
0
    XMEMCPY(buf, cipher, (size_t)len);
1283
0
    return buf;
1284
0
}
1285
1286
int wolfSSL_get_fd(const WOLFSSL* ssl)
1287
0
{
1288
0
    int fd = -1;
1289
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1290
0
    if (ssl) {
1291
0
        fd = ssl->rfd;
1292
0
    }
1293
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1294
0
    return fd;
1295
0
}
1296
1297
int wolfSSL_get_wfd(const WOLFSSL* ssl)
1298
0
{
1299
0
    int fd = -1;
1300
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1301
0
    if (ssl) {
1302
0
        fd = ssl->wfd;
1303
0
    }
1304
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1305
0
    return fd;
1306
0
}
1307
1308
1309
int wolfSSL_dtls(WOLFSSL* ssl)
1310
0
{
1311
0
    int dtlsOpt = 0;
1312
0
    if (ssl)
1313
0
        dtlsOpt = ssl->options.dtls;
1314
0
    return dtlsOpt;
1315
0
}
1316
1317
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
1318
1319
int wolfSSL_CTX_set_AcceptFilter(
1320
    WOLFSSL_CTX *ctx,
1321
    NetworkFilterCallback_t AcceptFilter,
1322
    void *AcceptFilter_arg)
1323
{
1324
    if (ctx == NULL)
1325
        return BAD_FUNC_ARG;
1326
    ctx->AcceptFilter = AcceptFilter;
1327
    ctx->AcceptFilter_arg = AcceptFilter_arg;
1328
    return 0;
1329
}
1330
1331
int wolfSSL_set_AcceptFilter(
1332
    WOLFSSL *ssl,
1333
    NetworkFilterCallback_t AcceptFilter,
1334
    void *AcceptFilter_arg)
1335
{
1336
    if (ssl == NULL)
1337
        return BAD_FUNC_ARG;
1338
    ssl->AcceptFilter = AcceptFilter;
1339
    ssl->AcceptFilter_arg = AcceptFilter_arg;
1340
    return 0;
1341
}
1342
1343
int wolfSSL_CTX_set_ConnectFilter(
1344
    WOLFSSL_CTX *ctx,
1345
    NetworkFilterCallback_t ConnectFilter,
1346
    void *ConnectFilter_arg)
1347
{
1348
    if (ctx == NULL)
1349
        return BAD_FUNC_ARG;
1350
    ctx->ConnectFilter = ConnectFilter;
1351
    ctx->ConnectFilter_arg = ConnectFilter_arg;
1352
    return 0;
1353
}
1354
1355
int wolfSSL_set_ConnectFilter(
1356
    WOLFSSL *ssl,
1357
    NetworkFilterCallback_t ConnectFilter,
1358
    void *ConnectFilter_arg)
1359
{
1360
    if (ssl == NULL)
1361
        return BAD_FUNC_ARG;
1362
    ssl->ConnectFilter = ConnectFilter;
1363
    ssl->ConnectFilter_arg = ConnectFilter_arg;
1364
    return 0;
1365
}
1366
1367
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
1368
1369
#ifndef WOLFSSL_LEANPSK
1370
#if defined(WOLFSSL_DTLS) && defined(XINET_PTON) && \
1371
    !defined(WOLFSSL_NO_SOCK) && defined(HAVE_SOCKADDR)
1372
void* wolfSSL_dtls_create_peer(int port, char* ip)
1373
{
1374
    SOCKADDR_IN *addr;
1375
    addr = (SOCKADDR_IN*)XMALLOC(sizeof(*addr), NULL,
1376
            DYNAMIC_TYPE_SOCKADDR);
1377
    if (addr == NULL) {
1378
        return NULL;
1379
    }
1380
1381
    addr->sin_family = AF_INET;
1382
    addr->sin_port = XHTONS((word16)port);
1383
    if (XINET_PTON(AF_INET, ip, &addr->sin_addr) < 1) {
1384
        XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1385
        return NULL;
1386
    }
1387
1388
    return addr;
1389
}
1390
1391
int wolfSSL_dtls_free_peer(void* addr)
1392
{
1393
    XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1394
    return WOLFSSL_SUCCESS;
1395
}
1396
#endif
1397
1398
#ifdef WOLFSSL_DTLS
1399
static int SockAddrSet(WOLFSSL_SOCKADDR* sockAddr, void* peer,
1400
                       unsigned int peerSz, void* heap)
1401
{
1402
    if (peer == NULL || peerSz == 0) {
1403
        if (sockAddr->sa != NULL)
1404
            XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR);
1405
        sockAddr->sa = NULL;
1406
        sockAddr->sz = 0;
1407
        sockAddr->bufSz = 0;
1408
        return WOLFSSL_SUCCESS;
1409
    }
1410
1411
    if (peerSz > sockAddr->bufSz) {
1412
        if (sockAddr->sa != NULL)
1413
            XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR);
1414
        sockAddr->sa =
1415
                (void*)XMALLOC(peerSz, heap, DYNAMIC_TYPE_SOCKADDR);
1416
        if (sockAddr->sa == NULL) {
1417
            sockAddr->sz = 0;
1418
            sockAddr->bufSz = 0;
1419
            return WOLFSSL_FAILURE;
1420
        }
1421
        sockAddr->bufSz = peerSz;
1422
    }
1423
    XMEMCPY(sockAddr->sa, peer, peerSz);
1424
    sockAddr->sz = peerSz;
1425
    return WOLFSSL_SUCCESS;
1426
}
1427
#endif
1428
1429
int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
1430
0
{
1431
#ifdef WOLFSSL_DTLS
1432
    int ret;
1433
1434
    if (ssl == NULL)
1435
        return WOLFSSL_FAILURE;
1436
#ifdef WOLFSSL_RW_THREADED
1437
    if (wc_LockRwLock_Wr(&ssl->buffers.dtlsCtx.peerLock) != 0)
1438
        return WOLFSSL_FAILURE;
1439
#endif
1440
    ret = SockAddrSet(&ssl->buffers.dtlsCtx.peer, peer, peerSz, ssl->heap);
1441
    if (ret == WOLFSSL_SUCCESS && !(peer == NULL || peerSz == 0))
1442
        ssl->buffers.dtlsCtx.userSet = 1;
1443
    else
1444
        ssl->buffers.dtlsCtx.userSet = 0;
1445
#ifdef WOLFSSL_RW_THREADED
1446
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
1447
        ret = WOLFSSL_FAILURE;
1448
#endif
1449
    return ret;
1450
#else
1451
0
    (void)ssl;
1452
0
    (void)peer;
1453
0
    (void)peerSz;
1454
0
    return WOLFSSL_NOT_IMPLEMENTED;
1455
0
#endif
1456
0
}
1457
1458
#if defined(WOLFSSL_DTLS_CID) && !defined(WOLFSSL_NO_SOCK)
1459
int wolfSSL_dtls_set_pending_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
1460
{
1461
#ifdef WOLFSSL_DTLS
1462
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
1463
1464
    if (ssl == NULL)
1465
        return WOLFSSL_FAILURE;
1466
#ifdef WOLFSSL_RW_THREADED
1467
    if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0)
1468
        return WOLFSSL_FAILURE;
1469
#endif
1470
    if (ssl->buffers.dtlsCtx.peer.sa != NULL &&
1471
            ssl->buffers.dtlsCtx.peer.sz == peerSz &&
1472
            sockAddrEqual((SOCKADDR_S*)ssl->buffers.dtlsCtx.peer.sa,
1473
                    (XSOCKLENT)ssl->buffers.dtlsCtx.peer.sz, (SOCKADDR_S*)peer,
1474
                    (XSOCKLENT)peerSz)) {
1475
        /* Already the current peer. */
1476
        if (ssl->buffers.dtlsCtx.pendingPeer.sa != NULL) {
1477
            /* Clear any other pendingPeer */
1478
            XFREE(ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->heap,
1479
                  DYNAMIC_TYPE_SOCKADDR);
1480
            ssl->buffers.dtlsCtx.pendingPeer.sa = NULL;
1481
            ssl->buffers.dtlsCtx.pendingPeer.sz = 0;
1482
            ssl->buffers.dtlsCtx.pendingPeer.bufSz = 0;
1483
        }
1484
        ret = WOLFSSL_SUCCESS;
1485
    }
1486
    else {
1487
        ret = SockAddrSet(&ssl->buffers.dtlsCtx.pendingPeer, peer, peerSz,
1488
                ssl->heap);
1489
    }
1490
    if (ret == WOLFSSL_SUCCESS)
1491
        ssl->buffers.dtlsCtx.processingPendingRecord = 0;
1492
#ifdef WOLFSSL_RW_THREADED
1493
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
1494
        ret = WOLFSSL_FAILURE;
1495
#endif
1496
    return ret;
1497
#else
1498
    (void)ssl;
1499
    (void)peer;
1500
    (void)peerSz;
1501
    return WOLFSSL_NOT_IMPLEMENTED;
1502
#endif
1503
}
1504
#endif /* WOLFSSL_DTLS_CID && !WOLFSSL_NO_SOCK */
1505
1506
int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz)
1507
0
{
1508
#ifdef WOLFSSL_DTLS
1509
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
1510
    if (ssl == NULL)
1511
        return WOLFSSL_FAILURE;
1512
#ifdef WOLFSSL_RW_THREADED
1513
    if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0)
1514
        return WOLFSSL_FAILURE;
1515
#endif
1516
    if (peer != NULL && peerSz != NULL
1517
            && *peerSz >= ssl->buffers.dtlsCtx.peer.sz
1518
            && ssl->buffers.dtlsCtx.peer.sa != NULL) {
1519
        *peerSz = ssl->buffers.dtlsCtx.peer.sz;
1520
        XMEMCPY(peer, ssl->buffers.dtlsCtx.peer.sa, *peerSz);
1521
        ret = WOLFSSL_SUCCESS;
1522
    }
1523
#ifdef WOLFSSL_RW_THREADED
1524
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
1525
        ret = WOLFSSL_FAILURE;
1526
#endif
1527
    return ret;
1528
#else
1529
0
    (void)ssl;
1530
0
    (void)peer;
1531
0
    (void)peerSz;
1532
0
    return WOLFSSL_NOT_IMPLEMENTED;
1533
0
#endif
1534
0
}
1535
1536
int wolfSSL_dtls_get0_peer(WOLFSSL* ssl, const void** peer,
1537
                           unsigned int* peerSz)
1538
0
{
1539
#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_RW_THREADED)
1540
    if (ssl == NULL)
1541
        return WOLFSSL_FAILURE;
1542
1543
    if (peer == NULL || peerSz == NULL)
1544
        return WOLFSSL_FAILURE;
1545
1546
    *peer = ssl->buffers.dtlsCtx.peer.sa;
1547
    *peerSz = ssl->buffers.dtlsCtx.peer.sz;
1548
    return WOLFSSL_SUCCESS;
1549
#else
1550
0
    (void)ssl;
1551
0
    (void)peer;
1552
0
    (void)peerSz;
1553
0
    return WOLFSSL_NOT_IMPLEMENTED;
1554
0
#endif
1555
0
}
1556
1557
1558
#if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS)
1559
1560
int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx)
1561
{
1562
    WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_sctp");
1563
1564
    if (ctx == NULL)
1565
        return BAD_FUNC_ARG;
1566
1567
    ctx->dtlsSctp = 1;
1568
    return WOLFSSL_SUCCESS;
1569
}
1570
1571
1572
int wolfSSL_dtls_set_sctp(WOLFSSL* ssl)
1573
{
1574
    WOLFSSL_ENTER("wolfSSL_dtls_set_sctp");
1575
1576
    if (ssl == NULL)
1577
        return BAD_FUNC_ARG;
1578
1579
    ssl->options.dtlsSctp = 1;
1580
    return WOLFSSL_SUCCESS;
1581
}
1582
1583
#endif /* WOLFSSL_DTLS && WOLFSSL_SCTP */
1584
1585
#if (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)) && \
1586
                                                           defined(WOLFSSL_DTLS)
1587
1588
int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, word16 newMtu)
1589
{
1590
    if (ctx == NULL || newMtu > MAX_RECORD_SIZE)
1591
        return BAD_FUNC_ARG;
1592
1593
    ctx->dtlsMtuSz = newMtu;
1594
    return WOLFSSL_SUCCESS;
1595
}
1596
1597
1598
int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu)
1599
{
1600
    if (ssl == NULL)
1601
        return BAD_FUNC_ARG;
1602
1603
    if (newMtu > MAX_RECORD_SIZE) {
1604
        ssl->error = BAD_FUNC_ARG;
1605
        return WOLFSSL_FAILURE;
1606
    }
1607
1608
    ssl->dtlsMtuSz = newMtu;
1609
    return WOLFSSL_SUCCESS;
1610
}
1611
1612
#ifdef OPENSSL_EXTRA
1613
/* Maps to compatibility API SSL_set_mtu and is same as wolfSSL_dtls_set_mtu,
1614
 * but expects only success or failure returns. */
1615
int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu)
1616
{
1617
    if (wolfSSL_dtls_set_mtu(ssl, mtu) == WOLFSSL_SUCCESS)
1618
        return WOLFSSL_SUCCESS;
1619
    else
1620
        return WOLFSSL_FAILURE;
1621
}
1622
#endif /* OPENSSL_EXTRA */
1623
1624
#endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */
1625
1626
#ifdef WOLFSSL_SRTP
1627
1628
static const WOLFSSL_SRTP_PROTECTION_PROFILE gSrtpProfiles[] = {
1629
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 80-bits
1630
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
1631
    {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80,
1632
     (((128 + 112) * 2) / 8) },
1633
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 32-bits
1634
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
1635
    {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32,
1636
     (((128 + 112) * 2) / 8) },
1637
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 80-bits */
1638
    {"SRTP_NULL_SHA1_80", SRTP_NULL_SHA1_80, ((112 * 2) / 8)},
1639
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 32-bits */
1640
    {"SRTP_NULL_SHA1_32", SRTP_NULL_SHA1_32, ((112 * 2) / 8)},
1641
    /* AES GCM 128, Salt: 96-bits, Auth GCM Tag 128-bits
1642
     * (master_key:128bits + master_salt:96bits) * 2 = 448 bits (56) */
1643
    {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM, (((128 + 96) * 2) / 8) },
1644
    /* AES GCM 256, Salt: 96-bits, Auth GCM Tag 128-bits
1645
     * (master_key:256bits + master_salt:96bits) * 2 = 704 bits (88) */
1646
    {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM, (((256 + 96) * 2) / 8) },
1647
};
1648
1649
static const WOLFSSL_SRTP_PROTECTION_PROFILE* DtlsSrtpFindProfile(
1650
    const char* profile_str, word32 profile_str_len, unsigned long id)
1651
{
1652
    int i;
1653
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1654
    for (i=0;
1655
         i<(int)(sizeof(gSrtpProfiles)/sizeof(WOLFSSL_SRTP_PROTECTION_PROFILE));
1656
         i++) {
1657
        if (profile_str != NULL) {
1658
            word32 srtp_profile_len = (word32)XSTRLEN(gSrtpProfiles[i].name);
1659
            if (srtp_profile_len == profile_str_len &&
1660
                XMEMCMP(gSrtpProfiles[i].name, profile_str, profile_str_len)
1661
                                                                         == 0) {
1662
                profile = &gSrtpProfiles[i];
1663
                break;
1664
            }
1665
        }
1666
        else if (id != 0 && gSrtpProfiles[i].id == id) {
1667
            profile = &gSrtpProfiles[i];
1668
            break;
1669
        }
1670
    }
1671
    return profile;
1672
}
1673
1674
/* profile_str: accepts ":" colon separated list of SRTP profiles */
1675
static int DtlsSrtpSelProfiles(word16* id, const char* profile_str)
1676
{
1677
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile;
1678
    const char *current, *next = NULL;
1679
    word32 length = 0, current_length;
1680
1681
    *id = 0; /* reset destination ID's */
1682
1683
    if (profile_str == NULL) {
1684
        return WOLFSSL_FAILURE;
1685
    }
1686
1687
    /* loop on end of line or colon ":" */
1688
    next = profile_str;
1689
    length = (word32)XSTRLEN(profile_str);
1690
    do {
1691
        current = next;
1692
        next = XSTRSTR(current, ":");
1693
        if (next) {
1694
            current_length = (word32)(next - current);
1695
            ++next; /* ++ needed to skip ':' */
1696
        } else {
1697
            current_length = (word32)XSTRLEN(current);
1698
        }
1699
        if (current_length < length)
1700
            length = current_length;
1701
        profile = DtlsSrtpFindProfile(current, current_length, 0);
1702
        if (profile != NULL) {
1703
            *id |= (1 << profile->id); /* selected bit based on ID */
1704
        }
1705
    } while (next != NULL);
1706
    return WOLFSSL_SUCCESS;
1707
}
1708
1709
/**
1710
 * @brief Set the SRTP protection profiles for DTLS.
1711
 *
1712
 * @param ctx Pointer to the WOLFSSL_CTX structure representing the SSL/TLS
1713
 *            context.
1714
 * @param profile_str A colon-separated string of SRTP profile names.
1715
 * @return 0 on success to match OpenSSL
1716
 * @return 1 on error to match OpenSSL
1717
 */
1718
int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str)
1719
{
1720
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
1721
    if (ctx != NULL) {
1722
        ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str);
1723
    }
1724
1725
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) {
1726
        ret = 1;
1727
    } else {
1728
        ret = 0;
1729
    }
1730
1731
    return ret;
1732
}
1733
1734
/**
1735
 * @brief Set the SRTP protection profiles for DTLS.
1736
 *
1737
 * @param ssl Pointer to the WOLFSSL structure representing the SSL/TLS
1738
 *            session.
1739
 * @param profile_str A colon-separated string of SRTP profile names.
1740
 * @return 0 on success to match OpenSSL
1741
 * @return 1 on error to match OpenSSL
1742
 */
1743
int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str)
1744
{
1745
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
1746
    if (ssl != NULL) {
1747
        ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str);
1748
    }
1749
1750
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) {
1751
        ret = 1;
1752
    } else {
1753
        ret = 0;
1754
    }
1755
1756
    return ret;
1757
}
1758
1759
const WOLFSSL_SRTP_PROTECTION_PROFILE* wolfSSL_get_selected_srtp_profile(
1760
    WOLFSSL* ssl)
1761
{
1762
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1763
    if (ssl) {
1764
        profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
1765
    }
1766
    return profile;
1767
}
1768
#ifndef NO_WOLFSSL_STUB
1769
WOLF_STACK_OF(WOLFSSL_SRTP_PROTECTION_PROFILE)* wolfSSL_get_srtp_profiles(
1770
    WOLFSSL* ssl)
1771
{
1772
    /* Not yet implemented - should return list of available SRTP profiles
1773
     * ssl->dtlsSrtpProfiles */
1774
    (void)ssl;
1775
    return NULL;
1776
}
1777
#endif
1778
1779
#define DTLS_SRTP_KEYING_MATERIAL_LABEL "EXTRACTOR-dtls_srtp"
1780
1781
int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl,
1782
    unsigned char* out, size_t* olen)
1783
{
1784
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1785
1786
    if (ssl == NULL || olen == NULL) {
1787
        return BAD_FUNC_ARG;
1788
    }
1789
1790
    profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
1791
    if (profile == NULL) {
1792
        WOLFSSL_MSG("Not using DTLS SRTP");
1793
        return EXT_MISSING;
1794
    }
1795
    if (out == NULL) {
1796
        *olen = (size_t)profile->kdfBits;
1797
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
1798
    }
1799
1800
    if (*olen < (size_t)profile->kdfBits) {
1801
        return BUFFER_E;
1802
    }
1803
1804
    return wolfSSL_export_keying_material(ssl, out, (size_t)profile->kdfBits,
1805
            DTLS_SRTP_KEYING_MATERIAL_LABEL,
1806
            XSTR_SIZEOF(DTLS_SRTP_KEYING_MATERIAL_LABEL), NULL, 0, 0);
1807
}
1808
1809
#endif /* WOLFSSL_SRTP */
1810
1811
1812
#ifdef WOLFSSL_DTLS_DROP_STATS
1813
1814
int wolfSSL_dtls_get_drop_stats(WOLFSSL* ssl,
1815
                                word32* macDropCount, word32* replayDropCount)
1816
{
1817
    int ret;
1818
1819
    WOLFSSL_ENTER("wolfSSL_dtls_get_drop_stats");
1820
1821
    if (ssl == NULL)
1822
        ret = BAD_FUNC_ARG;
1823
    else {
1824
        ret = WOLFSSL_SUCCESS;
1825
        if (macDropCount != NULL)
1826
            *macDropCount = ssl->macDropCount;
1827
        if (replayDropCount != NULL)
1828
            *replayDropCount = ssl->replayDropCount;
1829
    }
1830
1831
    WOLFSSL_LEAVE("wolfSSL_dtls_get_drop_stats", ret);
1832
    return ret;
1833
}
1834
1835
#endif /* WOLFSSL_DTLS_DROP_STATS */
1836
1837
1838
#if defined(WOLFSSL_MULTICAST)
1839
1840
int wolfSSL_CTX_mcast_set_member_id(WOLFSSL_CTX* ctx, word16 id)
1841
{
1842
    int ret = 0;
1843
1844
    WOLFSSL_ENTER("wolfSSL_CTX_mcast_set_member_id");
1845
1846
    if (ctx == NULL || id > WOLFSSL_MAX_8BIT)
1847
        ret = BAD_FUNC_ARG;
1848
1849
    if (ret == 0) {
1850
        ctx->haveEMS = 0;
1851
        ctx->haveMcast = 1;
1852
        ctx->mcastID = (byte)id;
1853
#ifndef WOLFSSL_USER_IO
1854
        ctx->CBIORecv = EmbedReceiveFromMcast;
1855
#endif /* WOLFSSL_USER_IO */
1856
1857
        ret = WOLFSSL_SUCCESS;
1858
    }
1859
    WOLFSSL_LEAVE("wolfSSL_CTX_mcast_set_member_id", ret);
1860
    return ret;
1861
}
1862
1863
int wolfSSL_mcast_get_max_peers(void)
1864
{
1865
    return WOLFSSL_MULTICAST_PEERS;
1866
}
1867
1868
#ifdef WOLFSSL_DTLS
1869
static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
1870
                                         word32 second, word32 high)
1871
{
1872
    word32 newCur = 0;
1873
1874
    if (cur < first)
1875
        newCur = first;
1876
    else if (cur < second)
1877
        newCur = second;
1878
    else if (cur < high)
1879
        newCur = high;
1880
1881
    return newCur;
1882
}
1883
#endif /* WOLFSSL_DTLS */
1884
1885
1886
int wolfSSL_set_secret(WOLFSSL* ssl, word16 epoch,
1887
                       const byte* preMasterSecret, word32 preMasterSz,
1888
                       const byte* clientRandom, const byte* serverRandom,
1889
                       const byte* suite)
1890
{
1891
    int ret = 0;
1892
1893
    WOLFSSL_ENTER("wolfSSL_set_secret");
1894
1895
    if (ssl == NULL || preMasterSecret == NULL ||
1896
        preMasterSz == 0 || preMasterSz > ENCRYPT_LEN ||
1897
        clientRandom == NULL || serverRandom == NULL || suite == NULL) {
1898
1899
        ret = BAD_FUNC_ARG;
1900
    }
1901
1902
    if (ret == 0 && ssl->arrays->preMasterSecret == NULL) {
1903
        ssl->arrays->preMasterSz = ENCRYPT_LEN;
1904
        ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
1905
            DYNAMIC_TYPE_SECRET);
1906
        if (ssl->arrays->preMasterSecret == NULL) {
1907
            ret = MEMORY_E;
1908
        }
1909
    }
1910
1911
    if (ret == 0) {
1912
        XMEMCPY(ssl->arrays->preMasterSecret, preMasterSecret, preMasterSz);
1913
        XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0,
1914
            ENCRYPT_LEN - preMasterSz);
1915
        ssl->arrays->preMasterSz = preMasterSz;
1916
        XMEMCPY(ssl->arrays->clientRandom, clientRandom, RAN_LEN);
1917
        XMEMCPY(ssl->arrays->serverRandom, serverRandom, RAN_LEN);
1918
        ssl->options.cipherSuite0 = suite[0];
1919
        ssl->options.cipherSuite = suite[1];
1920
1921
        ret = SetCipherSpecs(ssl);
1922
    }
1923
1924
    if (ret == 0)
1925
        ret = MakeTlsMasterSecret(ssl);
1926
1927
    if (ret == 0) {
1928
        ssl->keys.encryptionOn = 1;
1929
        ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
1930
    }
1931
1932
    if (ret == 0) {
1933
        if (ssl->options.dtls) {
1934
        #ifdef WOLFSSL_DTLS
1935
            WOLFSSL_DTLS_PEERSEQ* peerSeq;
1936
            int i;
1937
1938
            ssl->keys.dtls_epoch = epoch;
1939
            for (i = 0, peerSeq = ssl->keys.peerSeq;
1940
                 i < WOLFSSL_DTLS_PEERSEQ_SZ;
1941
                 i++, peerSeq++) {
1942
1943
                peerSeq->nextEpoch = epoch;
1944
                peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
1945
                peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
1946
                peerSeq->nextSeq_lo = 0;
1947
                peerSeq->nextSeq_hi = 0;
1948
                XMEMCPY(peerSeq->prevWindow, peerSeq->window, DTLS_SEQ_SZ);
1949
                XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
1950
                peerSeq->highwaterMark = UpdateHighwaterMark(0,
1951
                        ssl->ctx->mcastFirstSeq,
1952
                        ssl->ctx->mcastSecondSeq,
1953
                        ssl->ctx->mcastMaxSeq);
1954
            }
1955
        #else
1956
            (void)epoch;
1957
        #endif
1958
        }
1959
        FreeHandshakeResources(ssl);
1960
        ret = WOLFSSL_SUCCESS;
1961
    }
1962
    else {
1963
        if (ssl)
1964
            ssl->error = ret;
1965
        ret = WOLFSSL_FATAL_ERROR;
1966
    }
1967
    WOLFSSL_LEAVE("wolfSSL_set_secret", ret);
1968
    return ret;
1969
}
1970
1971
1972
#ifdef WOLFSSL_DTLS
1973
1974
int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub)
1975
{
1976
    WOLFSSL_DTLS_PEERSEQ* p = NULL;
1977
    int ret = WOLFSSL_SUCCESS;
1978
    int i;
1979
1980
    WOLFSSL_ENTER("wolfSSL_mcast_peer_add");
1981
    if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT)
1982
        return BAD_FUNC_ARG;
1983
1984
    if (!sub) {
1985
        /* Make sure it isn't already present, while keeping the first
1986
         * open spot. */
1987
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
1988
            if (ssl->keys.peerSeq[i].peerId == INVALID_PEER_ID)
1989
                p = &ssl->keys.peerSeq[i];
1990
            if (ssl->keys.peerSeq[i].peerId == peerId) {
1991
                WOLFSSL_MSG("Peer ID already in multicast peer list.");
1992
                p = NULL;
1993
            }
1994
        }
1995
1996
        if (p != NULL) {
1997
            XMEMSET(p, 0, sizeof(WOLFSSL_DTLS_PEERSEQ));
1998
            p->peerId = peerId;
1999
            p->highwaterMark = UpdateHighwaterMark(0,
2000
                ssl->ctx->mcastFirstSeq,
2001
                ssl->ctx->mcastSecondSeq,
2002
                ssl->ctx->mcastMaxSeq);
2003
        }
2004
        else {
2005
            WOLFSSL_MSG("No room in peer list.");
2006
            ret = WOLFSSL_FATAL_ERROR;
2007
        }
2008
    }
2009
    else {
2010
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
2011
            if (ssl->keys.peerSeq[i].peerId == peerId)
2012
                p = &ssl->keys.peerSeq[i];
2013
        }
2014
2015
        if (p != NULL) {
2016
            p->peerId = INVALID_PEER_ID;
2017
        }
2018
        else {
2019
            WOLFSSL_MSG("Peer not found in list.");
2020
        }
2021
    }
2022
2023
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_add", ret);
2024
    return ret;
2025
}
2026
2027
2028
/* If peerId is in the list of peers and its last sequence number is non-zero,
2029
 * return 1, otherwise return 0. */
2030
int wolfSSL_mcast_peer_known(WOLFSSL* ssl, unsigned short peerId)
2031
{
2032
    int known = 0;
2033
    int i;
2034
2035
    WOLFSSL_ENTER("wolfSSL_mcast_peer_known");
2036
2037
    if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT) {
2038
        return BAD_FUNC_ARG;
2039
    }
2040
2041
    for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
2042
        if (ssl->keys.peerSeq[i].peerId == peerId) {
2043
            if (ssl->keys.peerSeq[i].nextSeq_hi ||
2044
                ssl->keys.peerSeq[i].nextSeq_lo) {
2045
2046
                known = 1;
2047
            }
2048
            break;
2049
        }
2050
    }
2051
2052
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_known", known);
2053
    return known;
2054
}
2055
2056
2057
int wolfSSL_CTX_mcast_set_highwater_cb(WOLFSSL_CTX* ctx, word32 maxSeq,
2058
                                       word32 first, word32 second,
2059
                                       CallbackMcastHighwater cb)
2060
{
2061
    if (ctx == NULL || (second && first > second) ||
2062
        first > maxSeq || second > maxSeq || cb == NULL) {
2063
2064
        return BAD_FUNC_ARG;
2065
    }
2066
2067
    ctx->mcastHwCb = cb;
2068
    ctx->mcastFirstSeq = first;
2069
    ctx->mcastSecondSeq = second;
2070
    ctx->mcastMaxSeq = maxSeq;
2071
2072
    return WOLFSSL_SUCCESS;
2073
}
2074
2075
2076
int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx)
2077
{
2078
    if (ssl == NULL || ctx == NULL)
2079
        return BAD_FUNC_ARG;
2080
2081
    ssl->mcastHwCbCtx = ctx;
2082
2083
    return WOLFSSL_SUCCESS;
2084
}
2085
2086
#endif /* WOLFSSL_DTLS */
2087
2088
#endif /* WOLFSSL_MULTICAST */
2089
2090
2091
#endif /* WOLFSSL_LEANPSK */
2092
2093
#ifndef NO_TLS
2094
/* return underlying connect or accept, WOLFSSL_SUCCESS on ok */
2095
int wolfSSL_negotiate(WOLFSSL* ssl)
2096
256
{
2097
256
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
2098
2099
256
    WOLFSSL_ENTER("wolfSSL_negotiate");
2100
2101
256
    if (ssl == NULL)
2102
0
        return WOLFSSL_FATAL_ERROR;
2103
2104
256
#ifndef NO_WOLFSSL_SERVER
2105
256
    if (ssl->options.side == WOLFSSL_SERVER_END) {
2106
256
#ifdef WOLFSSL_TLS13
2107
256
        if (IsAtLeastTLSv1_3(ssl->version))
2108
256
            err = wolfSSL_accept_TLSv13(ssl);
2109
0
        else
2110
0
#endif
2111
0
            err = wolfSSL_accept(ssl);
2112
256
    }
2113
256
#endif
2114
2115
256
#ifndef NO_WOLFSSL_CLIENT
2116
256
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
2117
0
#ifdef WOLFSSL_TLS13
2118
0
        if (IsAtLeastTLSv1_3(ssl->version))
2119
0
            err = wolfSSL_connect_TLSv13(ssl);
2120
0
        else
2121
0
#endif
2122
0
            err = wolfSSL_connect(ssl);
2123
0
    }
2124
256
#endif
2125
2126
256
    (void)ssl;
2127
2128
256
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
2129
2130
256
    return err;
2131
256
}
2132
#endif /* !NO_TLS */
2133
2134
WOLFSSL_ABI
2135
WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
2136
0
{
2137
0
    if (ssl) {
2138
0
        return ssl->rng;
2139
0
    }
2140
2141
0
    return NULL;
2142
0
}
2143
2144
2145
#ifndef WOLFSSL_LEANPSK
2146
/* object size based on build */
2147
int wolfSSL_GetObjectSize(void)
2148
0
{
2149
#ifdef SHOW_SIZES
2150
    printf("sizeof suites           = %lu\n", (unsigned long)sizeof(Suites));
2151
    printf("sizeof ciphers(2)       = %lu\n", (unsigned long)sizeof(Ciphers));
2152
#ifndef NO_RC4
2153
    printf("\tsizeof arc4         = %lu\n", (unsigned long)sizeof(Arc4));
2154
#endif
2155
    printf("\tsizeof aes          = %lu\n", (unsigned long)sizeof(Aes));
2156
#ifndef NO_DES3
2157
    printf("\tsizeof des3         = %lu\n", (unsigned long)sizeof(Des3));
2158
#endif
2159
#ifdef HAVE_CHACHA
2160
    printf("\tsizeof chacha       = %lu\n", (unsigned long)sizeof(ChaCha));
2161
#endif
2162
#ifdef WOLFSSL_SM4
2163
    printf("\tsizeof sm4          = %lu\n", (unsigned long)sizeof(Sm4));
2164
#endif
2165
    printf("sizeof cipher specs     = %lu\n", (unsigned long)
2166
        sizeof(CipherSpecs));
2167
    printf("sizeof keys             = %lu\n", (unsigned long)sizeof(Keys));
2168
    printf("sizeof Hashes(2)        = %lu\n", (unsigned long)sizeof(Hashes));
2169
#ifndef NO_MD5
2170
    printf("\tsizeof MD5          = %lu\n", (unsigned long)sizeof(wc_Md5));
2171
#endif
2172
#ifndef NO_SHA
2173
    printf("\tsizeof SHA          = %lu\n", (unsigned long)sizeof(wc_Sha));
2174
#endif
2175
#ifdef WOLFSSL_SHA224
2176
    printf("\tsizeof SHA224       = %lu\n", (unsigned long)sizeof(wc_Sha224));
2177
#endif
2178
#ifndef NO_SHA256
2179
    printf("\tsizeof SHA256       = %lu\n", (unsigned long)sizeof(wc_Sha256));
2180
#endif
2181
#ifdef WOLFSSL_SHA384
2182
    printf("\tsizeof SHA384       = %lu\n", (unsigned long)sizeof(wc_Sha384));
2183
#endif
2184
#ifdef WOLFSSL_SHA384
2185
    printf("\tsizeof SHA512       = %lu\n", (unsigned long)sizeof(wc_Sha512));
2186
#endif
2187
#ifdef WOLFSSL_SM3
2188
    printf("\tsizeof sm3          = %lu\n", (unsigned long)sizeof(Sm3));
2189
#endif
2190
    printf("sizeof Buffers          = %lu\n", (unsigned long)sizeof(Buffers));
2191
    printf("sizeof Options          = %lu\n", (unsigned long)sizeof(Options));
2192
    printf("sizeof Arrays           = %lu\n", (unsigned long)sizeof(Arrays));
2193
#ifndef NO_RSA
2194
    printf("sizeof RsaKey           = %lu\n", (unsigned long)sizeof(RsaKey));
2195
#endif
2196
#ifdef HAVE_ECC
2197
    printf("sizeof ecc_key          = %lu\n", (unsigned long)sizeof(ecc_key));
2198
#endif
2199
    printf("sizeof WOLFSSL_CIPHER    = %lu\n", (unsigned long)
2200
        sizeof(WOLFSSL_CIPHER));
2201
    printf("sizeof WOLFSSL_SESSION   = %lu\n", (unsigned long)
2202
        sizeof(WOLFSSL_SESSION));
2203
    printf("sizeof WOLFSSL           = %lu\n", (unsigned long)sizeof(WOLFSSL));
2204
    printf("sizeof WOLFSSL_CTX       = %lu\n", (unsigned long)
2205
        sizeof(WOLFSSL_CTX));
2206
#endif
2207
2208
0
    return sizeof(WOLFSSL);
2209
0
}
2210
2211
int wolfSSL_CTX_GetObjectSize(void)
2212
0
{
2213
0
    return sizeof(WOLFSSL_CTX);
2214
0
}
2215
2216
int wolfSSL_METHOD_GetObjectSize(void)
2217
0
{
2218
0
    return sizeof(WOLFSSL_METHOD);
2219
0
}
2220
#endif
2221
2222
2223
#ifdef WOLFSSL_STATIC_MEMORY
2224
2225
int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx,
2226
    wolfSSL_method_func method, unsigned char* buf, unsigned int sz, int flag,
2227
    int maxSz)
2228
{
2229
    WOLFSSL_HEAP_HINT* hint = NULL;
2230
2231
    if (ctx == NULL || buf == NULL) {
2232
        return BAD_FUNC_ARG;
2233
    }
2234
2235
    if (*ctx == NULL && method == NULL) {
2236
        return BAD_FUNC_ARG;
2237
    }
2238
2239
    /* If there is a heap already, capture it in hint. */
2240
    if (*ctx && (*ctx)->heap != NULL) {
2241
        hint = (*ctx)->heap;
2242
    }
2243
2244
    if (wc_LoadStaticMemory(&hint, buf, sz, flag, maxSz)) {
2245
        WOLFSSL_MSG("Error loading static memory");
2246
        return WOLFSSL_FAILURE;
2247
    }
2248
2249
    if (*ctx) {
2250
        if ((*ctx)->heap == NULL) {
2251
            (*ctx)->heap = (void*)hint;
2252
        }
2253
    }
2254
    else {
2255
        /* create ctx if needed */
2256
        *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
2257
        if (*ctx == NULL) {
2258
            WOLFSSL_MSG("Error creating ctx");
2259
            return WOLFSSL_FAILURE;
2260
        }
2261
    }
2262
2263
    return WOLFSSL_SUCCESS;
2264
}
2265
2266
2267
int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
2268
{
2269
    if (ssl == NULL) {
2270
        return BAD_FUNC_ARG;
2271
    }
2272
    WOLFSSL_ENTER("wolfSSL_is_static_memory");
2273
2274
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
2275
    /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
2276
    if (mem_stats != NULL && ssl->heap != NULL) {
2277
        WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
2278
        WOLFSSL_HEAP* heap      = hint->memory;
2279
        if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
2280
            XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
2281
        }
2282
    }
2283
#endif
2284
2285
    (void)mem_stats;
2286
    return (ssl->heap) ? 1 : 0;
2287
}
2288
2289
2290
int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
2291
{
2292
    if (ctx == NULL) {
2293
        return BAD_FUNC_ARG;
2294
    }
2295
    WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
2296
2297
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
2298
    /* fill out statistics if wanted */
2299
    if (mem_stats != NULL && ctx->heap != NULL) {
2300
        WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
2301
        if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
2302
            return MEMORY_E;
2303
        }
2304
    }
2305
#endif
2306
2307
    (void)mem_stats;
2308
    return (ctx->heap) ? 1 : 0;
2309
}
2310
2311
#endif /* WOLFSSL_STATIC_MEMORY */
2312
2313
#ifndef NO_TLS
2314
/* return max record layer size plaintext input size */
2315
int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
2316
0
{
2317
0
    WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
2318
2319
0
    if (ssl == NULL)
2320
0
        return BAD_FUNC_ARG;
2321
2322
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE) {
2323
0
        WOLFSSL_MSG("Handshake not complete yet");
2324
0
        return BAD_FUNC_ARG;
2325
0
    }
2326
2327
0
    return min(OUTPUT_RECORD_SIZE, wolfssl_local_GetMaxPlaintextSize(ssl));
2328
0
}
2329
2330
2331
/* return record layer size of plaintext input size */
2332
int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
2333
0
{
2334
0
    int maxSize;
2335
2336
0
    WOLFSSL_ENTER("wolfSSL_GetOutputSize");
2337
2338
0
    if (inSz < 0)
2339
0
        return BAD_FUNC_ARG;
2340
2341
0
    maxSize = wolfSSL_GetMaxOutputSize(ssl);
2342
0
    if (maxSize < 0)
2343
0
        return maxSize;   /* error */
2344
0
    if (inSz > maxSize)
2345
0
        return INPUT_SIZE_E;
2346
2347
0
    return wolfssl_local_GetRecordSize(ssl, inSz, 1);
2348
0
}
2349
2350
2351
#ifdef HAVE_ECC
2352
int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2353
0
{
2354
0
    short keySzBytes;
2355
2356
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinEccKey_Sz");
2357
0
    if (ctx == NULL || keySz < 0) {
2358
0
        WOLFSSL_MSG("Key size must be positive value or ctx was null");
2359
0
        return BAD_FUNC_ARG;
2360
0
    }
2361
2362
0
    if (keySz % 8 == 0) {
2363
0
        keySzBytes = keySz / 8;
2364
0
    }
2365
0
    else {
2366
0
        keySzBytes = (keySz / 8) + 1;
2367
0
    }
2368
2369
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2370
    if (crypto_policy.enabled) {
2371
        if (ctx->minEccKeySz > (keySzBytes)) {
2372
            return CRYPTO_POLICY_FORBIDDEN;
2373
        }
2374
    }
2375
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2376
2377
0
    ctx->minEccKeySz     = keySzBytes;
2378
0
#ifndef NO_CERTS
2379
0
    ctx->cm->minEccKeySz = keySzBytes;
2380
0
#endif
2381
0
    return WOLFSSL_SUCCESS;
2382
0
}
2383
2384
2385
int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz)
2386
0
{
2387
0
    short keySzBytes;
2388
2389
0
    WOLFSSL_ENTER("wolfSSL_SetMinEccKey_Sz");
2390
0
    if (ssl == NULL || keySz < 0) {
2391
0
        WOLFSSL_MSG("Key size must be positive value or ctx was null");
2392
0
        return BAD_FUNC_ARG;
2393
0
    }
2394
2395
0
    if (keySz % 8 == 0) {
2396
0
        keySzBytes = keySz / 8;
2397
0
    }
2398
0
    else {
2399
0
        keySzBytes = (keySz / 8) + 1;
2400
0
    }
2401
2402
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2403
    if (crypto_policy.enabled) {
2404
        if (ssl->options.minEccKeySz > (keySzBytes)) {
2405
            return CRYPTO_POLICY_FORBIDDEN;
2406
        }
2407
    }
2408
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2409
2410
0
    ssl->options.minEccKeySz = keySzBytes;
2411
0
    return WOLFSSL_SUCCESS;
2412
0
}
2413
2414
#endif /* HAVE_ECC */
2415
2416
#ifndef NO_RSA
2417
int wolfSSL_CTX_SetMinRsaKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2418
0
{
2419
0
    if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
2420
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
2421
0
        return BAD_FUNC_ARG;
2422
0
    }
2423
2424
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2425
    if (crypto_policy.enabled) {
2426
        if (ctx->minRsaKeySz > (keySz / 8)) {
2427
            return CRYPTO_POLICY_FORBIDDEN;
2428
        }
2429
    }
2430
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2431
2432
0
    ctx->minRsaKeySz     = keySz / 8;
2433
0
    ctx->cm->minRsaKeySz = keySz / 8;
2434
0
    return WOLFSSL_SUCCESS;
2435
0
}
2436
2437
2438
int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz)
2439
0
{
2440
0
    if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
2441
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
2442
0
        return BAD_FUNC_ARG;
2443
0
    }
2444
2445
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2446
    if (crypto_policy.enabled) {
2447
        if (ssl->options.minRsaKeySz > (keySz / 8)) {
2448
            return CRYPTO_POLICY_FORBIDDEN;
2449
        }
2450
    }
2451
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2452
2453
0
    ssl->options.minRsaKeySz = keySz / 8;
2454
0
    return WOLFSSL_SUCCESS;
2455
0
}
2456
#endif /* !NO_RSA */
2457
2458
#ifndef NO_DH
2459
2460
#if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
2461
    !defined(HAVE_SELFTEST)
2462
/* Enables or disables the session's DH key prime test. */
2463
int wolfSSL_SetEnableDhKeyTest(WOLFSSL* ssl, int enable)
2464
0
{
2465
0
    WOLFSSL_ENTER("wolfSSL_SetEnableDhKeyTest");
2466
2467
0
    if (ssl == NULL)
2468
0
        return BAD_FUNC_ARG;
2469
2470
0
    if (!enable)
2471
0
        ssl->options.dhDoKeyTest = 0;
2472
0
    else
2473
0
        ssl->options.dhDoKeyTest = 1;
2474
2475
0
    WOLFSSL_LEAVE("wolfSSL_SetEnableDhKeyTest", WOLFSSL_SUCCESS);
2476
0
    return WOLFSSL_SUCCESS;
2477
0
}
2478
#endif
2479
2480
int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
2481
0
{
2482
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2483
0
        return BAD_FUNC_ARG;
2484
2485
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2486
    if (crypto_policy.enabled) {
2487
        if (ctx->minDhKeySz > (keySz_bits / 8)) {
2488
            return CRYPTO_POLICY_FORBIDDEN;
2489
        }
2490
    }
2491
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2492
2493
0
    ctx->minDhKeySz = keySz_bits / 8;
2494
0
    return WOLFSSL_SUCCESS;
2495
0
}
2496
2497
2498
int wolfSSL_SetMinDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
2499
0
{
2500
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2501
0
        return BAD_FUNC_ARG;
2502
2503
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2504
    if (crypto_policy.enabled) {
2505
        if (ssl->options.minDhKeySz > (keySz_bits / 8)) {
2506
            return CRYPTO_POLICY_FORBIDDEN;
2507
        }
2508
    }
2509
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2510
2511
0
    ssl->options.minDhKeySz = keySz_bits / 8;
2512
0
    return WOLFSSL_SUCCESS;
2513
0
}
2514
2515
2516
int wolfSSL_CTX_SetMaxDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
2517
0
{
2518
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2519
0
        return BAD_FUNC_ARG;
2520
2521
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2522
    if (crypto_policy.enabled) {
2523
        if (ctx->minDhKeySz > (keySz_bits / 8)) {
2524
            return CRYPTO_POLICY_FORBIDDEN;
2525
        }
2526
    }
2527
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2528
2529
0
    ctx->maxDhKeySz = keySz_bits / 8;
2530
0
    return WOLFSSL_SUCCESS;
2531
0
}
2532
2533
2534
int wolfSSL_SetMaxDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
2535
0
{
2536
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2537
0
        return BAD_FUNC_ARG;
2538
2539
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2540
    if (crypto_policy.enabled) {
2541
        if (ssl->options.minDhKeySz > (keySz_bits / 8)) {
2542
            return CRYPTO_POLICY_FORBIDDEN;
2543
        }
2544
    }
2545
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2546
2547
0
    ssl->options.maxDhKeySz = keySz_bits / 8;
2548
0
    return WOLFSSL_SUCCESS;
2549
0
}
2550
2551
2552
int wolfSSL_GetDhKey_Sz(WOLFSSL* ssl)
2553
0
{
2554
0
    if (ssl == NULL)
2555
0
        return BAD_FUNC_ARG;
2556
2557
0
    return (ssl->options.dhKeySz * 8);
2558
0
}
2559
2560
#endif /* !NO_DH */
2561
2562
2563
static int wolfSSL_write_internal(WOLFSSL* ssl, const void* data, size_t sz)
2564
{
2565
    int ret = 0;
2566
2567
    WOLFSSL_ENTER("wolfSSL_write");
2568
2569
    if (ssl == NULL || data == NULL)
2570
        return BAD_FUNC_ARG;
2571
2572
#ifdef WOLFSSL_QUIC
2573
    if (WOLFSSL_IS_QUIC(ssl)) {
2574
        WOLFSSL_MSG("SSL_write() on QUIC not allowed");
2575
        return BAD_FUNC_ARG;
2576
    }
2577
#endif
2578
2579
#ifdef HAVE_WRITE_DUP
2580
    if (ssl->dupSide == READ_DUP_SIDE) {
2581
        WOLFSSL_MSG("Read dup side cannot write");
2582
        return WRITE_DUP_WRITE_E;
2583
    }
2584
    /* Only enter special dupWrite logic when error is cleared. This will help
2585
     * with handling async data and other edge case errors. */
2586
    if (ssl->dupWrite != NULL && ssl->error == 0) {
2587
        int dupErr = 0;   /* local copy */
2588
        /* Lock ssl->dupWrite to gather what needs to be done. */
2589
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
2590
            return BAD_MUTEX_E;
2591
        dupErr = ssl->dupWrite->dupErr;
2592
#ifdef WOLFSSL_TLS13
2593
        if (IsAtLeastTLSv1_3(ssl->version)) {
2594
            /* TLS 1.3: if the read side received a KeyUpdate(update_requested)
2595
             * it cannot respond; send the response from here. */
2596
            ssl->keys.keyUpdateRespond |= ssl->dupWrite->keyUpdateRespond;
2597
            ssl->dupWrite->keyUpdateRespond = 0;
2598
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
2599
            ssl->postHandshakeAuthPending |=
2600
                    ssl->dupWrite->postHandshakeAuthPending;
2601
            ssl->dupWrite->postHandshakeAuthPending = 0;
2602
            if (ssl->postHandshakeAuthPending) {
2603
                /* Take ownership of the delegated auth state. */
2604
                CertReqCtx** tail = &ssl->dupWrite->postHandshakeCertReqCtx;
2605
                while (*tail != NULL)
2606
                    tail = &(*tail)->next;
2607
                *tail = ssl->certReqCtx;
2608
                ssl->certReqCtx = ssl->dupWrite->postHandshakeCertReqCtx;
2609
                ssl->dupWrite->postHandshakeCertReqCtx = NULL;
2610
                FreeHandshakeHashes(ssl);
2611
                ssl->hsHashes = ssl->dupWrite->postHandshakeHashState;
2612
                ssl->dupWrite->postHandshakeHashState = NULL;
2613
                ssl->options.sendVerify = ssl->dupWrite->postHandshakeSendVerify;
2614
                ssl->options.sigAlgo = ssl->dupWrite->postHandshakeSigAlgo;
2615
                ssl->options.hashAlgo = ssl->dupWrite->postHandshakeHashAlgo;
2616
            }
2617
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
2618
#ifdef WOLFSSL_DTLS13
2619
            if (ssl->options.dtls) {
2620
                /* Schedule key update to be sent. */
2621
                if (ssl->keys.keyUpdateRespond)
2622
                    ssl->dtls13DoKeyUpdate = 1;
2623
2624
                /* Copy over ACKs */
2625
                ssl->dtls13Rtx.sendAcks |= ssl->dupWrite->sendAcks;
2626
                if (ssl->dupWrite->sendAcks) {
2627
                    /* Insert each record number so the
2628
                     * ACK message is properly ordered. */
2629
                    struct Dtls13RecordNumber* rn;
2630
                    for (rn = ssl->dupWrite->sendAckList; rn != NULL;
2631
                         rn = rn->next) {
2632
                        ret = Dtls13RtxAddAck(ssl, rn->epoch, rn->seq);
2633
                        if (ret != 0)
2634
                            break;
2635
                    }
2636
                    /* Clear only on success so no ACKs get dropped */
2637
                    if (ret == 0) {
2638
                        rn = ssl->dupWrite->sendAckList;
2639
                        ssl->dupWrite->sendAckList = NULL;
2640
                        ssl->dupWrite->sendAcks = 0;
2641
                        while (rn != NULL) {
2642
                            struct Dtls13RecordNumber* next = rn->next;
2643
                            XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
2644
                            rn = next;
2645
                        }
2646
                    }
2647
                }
2648
2649
                /* Remove KeyUpdate record from RTX list. */
2650
                if (ssl->dupWrite->keyUpdateAcked) {
2651
                    Dtls13RtxRemoveRecord(ssl, ssl->dupWrite->keyUpdateEpoch,
2652
                            ssl->dupWrite->keyUpdateSeq);
2653
                }
2654
                /* Store if KeyUpdate was ACKed. */
2655
                ssl->dtls13KeyUpdateAcked |= ssl->dupWrite->keyUpdateAcked;
2656
                ssl->dupWrite->keyUpdateAcked = 0;
2657
            }
2658
#endif /* WOLFSSL_DTLS13 */
2659
        }
2660
#endif /* WOLFSSL_TLS13 */
2661
        wc_UnLockMutex(&ssl->dupWrite->dupMutex);
2662
2663
        if (dupErr != 0) {
2664
            WOLFSSL_MSG("Write dup error from other side");
2665
            ssl->error = dupErr;
2666
            return WOLFSSL_FATAL_ERROR;
2667
        }
2668
        if (ret != 0) {
2669
            ssl->error = ret;
2670
            return WOLFSSL_FATAL_ERROR;
2671
        }
2672
2673
2674
#ifdef WOLFSSL_TLS13
2675
        if (IsAtLeastTLSv1_3(ssl->version)) {
2676
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
2677
            /* Read side received a CertificateRequest but couldn't write;
2678
             * send Certificate+CertificateVerify+Finished from the write side. */
2679
            if (ssl->postHandshakeAuthPending) {
2680
                /* reset handshake states */
2681
                ssl->postHandshakeAuthPending = 0;
2682
                ssl->options.clientState = CLIENT_HELLO_COMPLETE;
2683
                ssl->options.connectState = FIRST_REPLY_DONE;
2684
                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
2685
                ssl->options.processReply = 0; /* doProcessInit */
2686
                if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
2687
                    if (ssl->error != WC_NO_ERR_TRACE(WANT_WRITE) &&
2688
                            ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) {
2689
                        WOLFSSL_MSG("Post-handshake auth send failed");
2690
                        ssl->error = POST_HAND_AUTH_ERROR;
2691
                    }
2692
                    return WOLFSSL_FATAL_ERROR;
2693
                }
2694
            }
2695
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
2696
#ifdef WOLFSSL_DTLS13
2697
            if (ssl->options.dtls) {
2698
                if (ssl->dtls13KeyUpdateAcked)
2699
                    ret = DoDtls13KeyUpdateAck(ssl);
2700
                ssl->dtls13KeyUpdateAcked = 0;
2701
                if (ret == 0)
2702
                    ret = Dtls13DoScheduledWork(ssl);
2703
            }
2704
            else
2705
#endif /* WOLFSSL_DTLS13 */
2706
            if (ssl->keys.keyUpdateRespond) /* cleared in SendTls13KeyUpdate */
2707
                ret = Tls13UpdateKeys(ssl);
2708
            if (ret != 0) {
2709
                ssl->error = ret;
2710
                return WOLFSSL_FATAL_ERROR;
2711
            }
2712
            /* WANT_WRITE is safe to clear. Data is buffered in output buffer
2713
             * or in DTLS RTX queue */
2714
            ret = 0;
2715
        }
2716
#endif /* WOLFSSL_TLS13 */
2717
    }
2718
#endif
2719
2720
#ifdef HAVE_ERRNO_H
2721
    errno = 0;
2722
#endif
2723
2724
    #ifdef OPENSSL_EXTRA
2725
    if (ssl->CBIS != NULL) {
2726
        ssl->CBIS(ssl, WOLFSSL_CB_WRITE, WOLFSSL_SUCCESS);
2727
        ssl->cbmode = WOLFSSL_CB_WRITE;
2728
    }
2729
    #endif
2730
    ret = SendData(ssl, data, sz);
2731
2732
    WOLFSSL_LEAVE("wolfSSL_write", ret);
2733
2734
    if (ret < 0)
2735
        return WOLFSSL_FATAL_ERROR;
2736
    else
2737
        return ret;
2738
}
2739
2740
WOLFSSL_ABI
2741
int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
2742
256
{
2743
256
    WOLFSSL_ENTER("wolfSSL_write");
2744
2745
256
    if (sz < 0)
2746
0
        return BAD_FUNC_ARG;
2747
2748
256
    return wolfSSL_write_internal(ssl, data, (size_t)sz);
2749
256
}
2750
2751
int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz)
2752
0
{
2753
0
    int maxLength;
2754
0
    int usedLength;
2755
2756
0
    WOLFSSL_ENTER("wolfSSL_inject");
2757
2758
0
    if (ssl == NULL || data == NULL || sz <= 0)
2759
0
        return BAD_FUNC_ARG;
2760
2761
0
    usedLength = (int)(ssl->buffers.inputBuffer.length -
2762
0
                       ssl->buffers.inputBuffer.idx);
2763
0
    maxLength  = (int)(ssl->buffers.inputBuffer.bufferSize -
2764
0
                       (word32)usedLength);
2765
2766
0
    if (sz > maxLength) {
2767
        /* Need to make space */
2768
0
        int ret;
2769
0
        if (ssl->buffers.clearOutputBuffer.length > 0) {
2770
            /* clearOutputBuffer points into so reallocating inputBuffer will
2771
             * invalidate clearOutputBuffer and lose app data */
2772
0
            WOLFSSL_MSG("Can't inject while there is application data to read");
2773
0
            return APP_DATA_READY;
2774
0
        }
2775
0
        ret = GrowInputBuffer(ssl, sz, usedLength);
2776
0
        if (ret < 0)
2777
0
            return ret;
2778
0
    }
2779
2780
0
    XMEMCPY(ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
2781
0
            data, sz);
2782
0
    ssl->buffers.inputBuffer.length += sz;
2783
2784
0
    return WOLFSSL_SUCCESS;
2785
0
}
2786
2787
2788
int wolfSSL_write_ex(WOLFSSL* ssl, const void* data, size_t sz, size_t* wr)
2789
0
{
2790
0
    int ret;
2791
2792
0
    if (wr != NULL) {
2793
0
        *wr = 0;
2794
0
    }
2795
2796
0
    ret = wolfSSL_write_internal(ssl, data, sz);
2797
0
    if (ret >= 0) {
2798
0
        if (wr != NULL) {
2799
0
            *wr = (size_t)ret;
2800
0
        }
2801
2802
        /* handle partial write cases, if not set then a partial write is
2803
         * considered a failure case, or if set and ret is 0 then is a fail */
2804
0
        if (ret == 0 && ssl->options.partialWrite) {
2805
0
            ret = 0;
2806
0
        }
2807
0
        else if ((size_t)ret < sz && !ssl->options.partialWrite) {
2808
0
            ret = 0;
2809
0
        }
2810
0
        else {
2811
            /* wrote out all application data, or wrote out 1 byte or more with
2812
             * partial write flag set */
2813
0
            ret = 1;
2814
0
        }
2815
0
    }
2816
0
    else {
2817
0
        ret = 0;
2818
0
    }
2819
2820
0
    return ret;
2821
0
}
2822
2823
2824
static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, size_t sz, int peek)
2825
{
2826
    int ret;
2827
2828
    WOLFSSL_ENTER("wolfSSL_read_internal");
2829
2830
    if (ssl == NULL || data == NULL)
2831
        return BAD_FUNC_ARG;
2832
2833
#ifdef WOLFSSL_QUIC
2834
    if (WOLFSSL_IS_QUIC(ssl)) {
2835
        WOLFSSL_MSG("SSL_read() on QUIC not allowed");
2836
        return BAD_FUNC_ARG;
2837
    }
2838
#endif
2839
#if defined(WOLFSSL_ERROR_CODE_OPENSSL) && defined(OPENSSL_EXTRA)
2840
    /* This additional logic is meant to simulate following openSSL behavior:
2841
     * After bidirectional SSL_shutdown complete, SSL_read returns 0 and
2842
     * SSL_get_error_code returns SSL_ERROR_ZERO_RETURN.
2843
     * This behavior is used to know the disconnect of the underlying
2844
     * transport layer.
2845
     *
2846
     * In this logic, CBIORecv is called with a read size of 0 to check the
2847
     * transport layer status. It also returns WOLFSSL_FAILURE so that
2848
     * SSL_read does not return a positive number on failure.
2849
     */
2850
2851
    /* make sure bidirectional TLS shutdown completes */
2852
    if (ssl->error == WOLFSSL_ERROR_SYSCALL || ssl->options.shutdownDone) {
2853
        /* ask the underlying transport the connection is closed */
2854
        if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx)
2855
            == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE))
2856
        {
2857
            ssl->options.isClosed = 1;
2858
            ssl->error = WOLFSSL_ERROR_ZERO_RETURN;
2859
        }
2860
        return WOLFSSL_FAILURE;
2861
    }
2862
#endif
2863
2864
#ifdef HAVE_WRITE_DUP
2865
    if (ssl->dupWrite && ssl->dupSide == WRITE_DUP_SIDE) {
2866
        WOLFSSL_MSG("Write dup side cannot read");
2867
        return WRITE_DUP_READ_E;
2868
    }
2869
#endif
2870
2871
#ifdef HAVE_ERRNO_H
2872
        errno = 0;
2873
#endif
2874
2875
    ret = ReceiveData(ssl, (byte*)data, sz, peek);
2876
2877
#ifdef HAVE_WRITE_DUP
2878
    if (ssl->dupWrite) {
2879
        if (ssl->error != 0 && ssl->error != WC_NO_ERR_TRACE(WANT_READ)
2880
        #ifdef WOLFSSL_ASYNC_CRYPT
2881
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
2882
        #endif
2883
        ) {
2884
            int notifyErr;
2885
2886
            WOLFSSL_MSG("Notifying write side of fatal read error");
2887
            notifyErr  = NotifyWriteSide(ssl, ssl->error);
2888
            if (notifyErr < 0) {
2889
                ret = ssl->error = notifyErr;
2890
            }
2891
        }
2892
    }
2893
#endif
2894
2895
    WOLFSSL_LEAVE("wolfSSL_read_internal", ret);
2896
2897
    if (ret < 0)
2898
        return WOLFSSL_FATAL_ERROR;
2899
    else
2900
        return ret;
2901
}
2902
2903
2904
int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz)
2905
0
{
2906
0
    WOLFSSL_ENTER("wolfSSL_peek");
2907
2908
0
    if (sz < 0)
2909
0
        return BAD_FUNC_ARG;
2910
2911
0
    return wolfSSL_read_internal(ssl, data, (size_t)sz, TRUE);
2912
0
}
2913
2914
2915
WOLFSSL_ABI
2916
int wolfSSL_read(WOLFSSL* ssl, void* data, int sz)
2917
{
2918
    WOLFSSL_ENTER("wolfSSL_read");
2919
2920
    if (sz < 0)
2921
        return BAD_FUNC_ARG;
2922
2923
    #ifdef OPENSSL_EXTRA
2924
    if (ssl == NULL) {
2925
        return BAD_FUNC_ARG;
2926
    }
2927
    if (ssl->CBIS != NULL) {
2928
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
2929
        ssl->cbmode = WOLFSSL_CB_READ;
2930
    }
2931
    #endif
2932
    return wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
2933
}
2934
2935
2936
/* returns 0 on failure and 1 on read */
2937
int wolfSSL_read_ex(WOLFSSL* ssl, void* data, size_t sz, size_t* rd)
2938
0
{
2939
0
    int ret;
2940
2941
    #ifdef OPENSSL_EXTRA
2942
    if (ssl == NULL) {
2943
        return BAD_FUNC_ARG;
2944
    }
2945
    if (ssl->CBIS != NULL) {
2946
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
2947
        ssl->cbmode = WOLFSSL_CB_READ;
2948
    }
2949
    #endif
2950
0
    ret = wolfSSL_read_internal(ssl, data, sz, FALSE);
2951
2952
0
    if (ret > 0 && rd != NULL) {
2953
0
        *rd = (size_t)ret;
2954
0
    }
2955
2956
0
    return ret > 0 ? 1 : 0;
2957
0
}
2958
2959
#ifdef WOLFSSL_MULTICAST
2960
2961
int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz)
2962
{
2963
    int ret = 0;
2964
2965
    WOLFSSL_ENTER("wolfSSL_mcast_read");
2966
2967
    if ((ssl == NULL) || (sz < 0))
2968
        return BAD_FUNC_ARG;
2969
2970
    ret = wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
2971
    if (ssl->options.dtls && ssl->options.haveMcast && id != NULL)
2972
        *id = ssl->keys.curPeerId;
2973
    return ret;
2974
}
2975
2976
#endif /* WOLFSSL_MULTICAST */
2977
#endif /* !NO_TLS */
2978
2979
/* helpers to set the device id, WOLFSSL_SUCCESS on ok */
2980
WOLFSSL_ABI
2981
int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
2982
0
{
2983
0
    if (ssl == NULL)
2984
0
        return BAD_FUNC_ARG;
2985
2986
0
    ssl->devId = devId;
2987
2988
0
    return WOLFSSL_SUCCESS;
2989
0
}
2990
2991
WOLFSSL_ABI
2992
int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
2993
0
{
2994
0
    if (ctx == NULL)
2995
0
        return BAD_FUNC_ARG;
2996
2997
0
    ctx->devId = devId;
2998
2999
0
    return WOLFSSL_SUCCESS;
3000
0
}
3001
3002
/* helpers to get device id and heap */
3003
WOLFSSL_ABI
3004
int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
3005
40
{
3006
40
    int devId = INVALID_DEVID;
3007
40
    if (ssl != NULL)
3008
0
        devId = ssl->devId;
3009
40
    if (ctx != NULL && devId == INVALID_DEVID)
3010
40
        devId = ctx->devId;
3011
40
    return devId;
3012
40
}
3013
void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
3014
0
{
3015
0
    void* heap = NULL;
3016
0
    if (ctx != NULL)
3017
0
        heap = ctx->heap;
3018
0
    else if (ssl != NULL)
3019
0
        heap = ssl->heap;
3020
0
    return heap;
3021
0
}
3022
3023
3024
#ifndef NO_TLS
3025
#ifdef HAVE_SNI
3026
3027
WOLFSSL_ABI
3028
int wolfSSL_UseSNI(WOLFSSL* ssl, byte type, const void* data, word16 size)
3029
0
{
3030
0
    if (ssl == NULL)
3031
0
        return BAD_FUNC_ARG;
3032
3033
0
    return TLSX_UseSNI(&ssl->extensions, type, data, size, ssl->heap);
3034
0
}
3035
3036
3037
WOLFSSL_ABI
3038
int wolfSSL_CTX_UseSNI(WOLFSSL_CTX* ctx, byte type, const void* data,
3039
                                                                    word16 size)
3040
28
{
3041
28
    if (ctx == NULL)
3042
0
        return BAD_FUNC_ARG;
3043
3044
28
    return TLSX_UseSNI(&ctx->extensions, type, data, size, ctx->heap);
3045
28
}
3046
3047
#ifndef NO_WOLFSSL_SERVER
3048
3049
void wolfSSL_SNI_SetOptions(WOLFSSL* ssl, byte type, byte options)
3050
0
{
3051
0
    if (ssl && ssl->extensions)
3052
0
        TLSX_SNI_SetOptions(ssl->extensions, type, options);
3053
0
}
3054
3055
3056
void wolfSSL_CTX_SNI_SetOptions(WOLFSSL_CTX* ctx, byte type, byte options)
3057
0
{
3058
0
    if (ctx && ctx->extensions)
3059
0
        TLSX_SNI_SetOptions(ctx->extensions, type, options);
3060
0
}
3061
3062
3063
byte wolfSSL_SNI_Status(WOLFSSL* ssl, byte type)
3064
0
{
3065
0
    return TLSX_SNI_Status(ssl ? ssl->extensions : NULL, type);
3066
0
}
3067
3068
3069
word16 wolfSSL_SNI_GetRequest(WOLFSSL* ssl, byte type, void** data)
3070
0
{
3071
0
    if (data)
3072
0
        *data = NULL;
3073
3074
0
    if (ssl && ssl->extensions)
3075
0
        return TLSX_SNI_GetRequest(ssl->extensions, type, data, 0);
3076
3077
0
    return 0;
3078
0
}
3079
3080
3081
int wolfSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
3082
                              byte type, byte* sni, word32* inOutSz)
3083
0
{
3084
0
    if (clientHello && helloSz > 0 && sni && inOutSz && *inOutSz > 0)
3085
0
        return TLSX_SNI_GetFromBuffer(clientHello, helloSz, type, sni, inOutSz);
3086
3087
0
    return BAD_FUNC_ARG;
3088
0
}
3089
3090
#endif /* !NO_WOLFSSL_SERVER */
3091
3092
#endif /* HAVE_SNI */
3093
3094
3095
#ifdef HAVE_TRUSTED_CA
3096
3097
int wolfSSL_UseTrustedCA(WOLFSSL* ssl, byte type,
3098
    const byte* certId, word32 certIdSz)
3099
{
3100
    if (ssl == NULL)
3101
        return BAD_FUNC_ARG;
3102
3103
    if (type == WOLFSSL_TRUSTED_CA_PRE_AGREED) {
3104
        if (certId != NULL || certIdSz != 0)
3105
            return BAD_FUNC_ARG;
3106
    }
3107
    else if (type == WOLFSSL_TRUSTED_CA_X509_NAME) {
3108
        if (certId == NULL || certIdSz == 0)
3109
            return BAD_FUNC_ARG;
3110
    }
3111
    #ifndef NO_SHA
3112
    else if (type == WOLFSSL_TRUSTED_CA_KEY_SHA1 ||
3113
            type == WOLFSSL_TRUSTED_CA_CERT_SHA1) {
3114
        if (certId == NULL || certIdSz != WC_SHA_DIGEST_SIZE)
3115
            return BAD_FUNC_ARG;
3116
    }
3117
    #endif
3118
    else
3119
        return BAD_FUNC_ARG;
3120
3121
    return TLSX_UseTrustedCA(&ssl->extensions,
3122
            type, certId, certIdSz, ssl->heap);
3123
}
3124
3125
#endif /* HAVE_TRUSTED_CA */
3126
3127
3128
#ifdef HAVE_MAX_FRAGMENT
3129
#ifndef NO_WOLFSSL_CLIENT
3130
3131
int wolfSSL_UseMaxFragment(WOLFSSL* ssl, byte mfl)
3132
{
3133
    if (ssl == NULL)
3134
        return BAD_FUNC_ARG;
3135
3136
#ifdef WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST
3137
    /* The following is a non-standard way to reconfigure the max packet size
3138
        post-handshake for wolfSSL_write/wolfSSL_read */
3139
    if (ssl->options.handShakeState == HANDSHAKE_DONE) {
3140
        switch (mfl) {
3141
            case WOLFSSL_MFL_2_8 : ssl->max_fragment =  256; break;
3142
            case WOLFSSL_MFL_2_9 : ssl->max_fragment =  512; break;
3143
            case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
3144
            case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
3145
            case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
3146
            case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
3147
            default: ssl->max_fragment = MAX_RECORD_SIZE; break;
3148
        }
3149
        return WOLFSSL_SUCCESS;
3150
    }
3151
#endif /* WOLFSSL_MAX_FRAGMENT_ADJUST */
3152
3153
    /* This call sets the max fragment TLS extension, which gets sent to server.
3154
        The server_hello response is what sets the `ssl->max_fragment` in
3155
        TLSX_MFL_Parse */
3156
    return TLSX_UseMaxFragment(&ssl->extensions, mfl, ssl->heap);
3157
}
3158
3159
3160
int wolfSSL_CTX_UseMaxFragment(WOLFSSL_CTX* ctx, byte mfl)
3161
{
3162
    if (ctx == NULL)
3163
        return BAD_FUNC_ARG;
3164
3165
    return TLSX_UseMaxFragment(&ctx->extensions, mfl, ctx->heap);
3166
}
3167
3168
#endif /* NO_WOLFSSL_CLIENT */
3169
#endif /* HAVE_MAX_FRAGMENT */
3170
3171
#ifdef HAVE_TRUNCATED_HMAC
3172
#ifndef NO_WOLFSSL_CLIENT
3173
3174
int wolfSSL_UseTruncatedHMAC(WOLFSSL* ssl)
3175
{
3176
    if (ssl == NULL)
3177
        return BAD_FUNC_ARG;
3178
3179
    return TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
3180
}
3181
3182
3183
int wolfSSL_CTX_UseTruncatedHMAC(WOLFSSL_CTX* ctx)
3184
{
3185
    if (ctx == NULL)
3186
        return BAD_FUNC_ARG;
3187
3188
    return TLSX_UseTruncatedHMAC(&ctx->extensions, ctx->heap);
3189
}
3190
3191
#endif /* NO_WOLFSSL_CLIENT */
3192
#endif /* HAVE_TRUNCATED_HMAC */
3193
3194
/* Elliptic Curves */
3195
#if defined(HAVE_SUPPORTED_CURVES)
3196
3197
static int isValidCurveGroup(word16 name)
3198
0
{
3199
0
    switch (name) {
3200
0
        case WOLFSSL_ECC_SECP160K1:
3201
0
        case WOLFSSL_ECC_SECP160R1:
3202
0
        case WOLFSSL_ECC_SECP160R2:
3203
0
        case WOLFSSL_ECC_SECP192K1:
3204
0
        case WOLFSSL_ECC_SECP192R1:
3205
0
        case WOLFSSL_ECC_SECP224K1:
3206
0
        case WOLFSSL_ECC_SECP224R1:
3207
0
        case WOLFSSL_ECC_SECP256K1:
3208
0
        case WOLFSSL_ECC_SECP256R1:
3209
0
        case WOLFSSL_ECC_SECP384R1:
3210
0
        case WOLFSSL_ECC_SECP521R1:
3211
0
        case WOLFSSL_ECC_BRAINPOOLP256R1:
3212
0
        case WOLFSSL_ECC_BRAINPOOLP384R1:
3213
0
        case WOLFSSL_ECC_BRAINPOOLP512R1:
3214
0
        case WOLFSSL_ECC_SM2P256V1:
3215
0
        case WOLFSSL_ECC_X25519:
3216
0
        case WOLFSSL_ECC_X448:
3217
0
        case WOLFSSL_ECC_BRAINPOOLP256R1TLS13:
3218
0
        case WOLFSSL_ECC_BRAINPOOLP384R1TLS13:
3219
0
        case WOLFSSL_ECC_BRAINPOOLP512R1TLS13:
3220
3221
0
        case WOLFSSL_FFDHE_2048:
3222
0
        case WOLFSSL_FFDHE_3072:
3223
0
        case WOLFSSL_FFDHE_4096:
3224
0
        case WOLFSSL_FFDHE_6144:
3225
0
        case WOLFSSL_FFDHE_8192:
3226
3227
0
#ifdef WOLFSSL_HAVE_MLKEM
3228
0
#ifndef WOLFSSL_NO_ML_KEM
3229
    #ifndef WOLFSSL_TLS_NO_MLKEM_STANDALONE
3230
        case WOLFSSL_ML_KEM_512:
3231
        case WOLFSSL_ML_KEM_768:
3232
        case WOLFSSL_ML_KEM_1024:
3233
    #endif /* !WOLFSSL_TLS_NO_MLKEM_STANDALONE */
3234
0
    #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)
3235
0
        #ifdef WOLFSSL_PQC_HYBRIDS
3236
0
        case WOLFSSL_SECP384R1MLKEM1024:
3237
0
        case WOLFSSL_X25519MLKEM768:
3238
0
        case WOLFSSL_SECP256R1MLKEM768:
3239
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
3240
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
3241
        case WOLFSSL_SECP256R1MLKEM512:
3242
        case WOLFSSL_SECP384R1MLKEM768:
3243
        case WOLFSSL_SECP521R1MLKEM1024:
3244
        case WOLFSSL_X25519MLKEM512:
3245
        case WOLFSSL_X448MLKEM768:
3246
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
3247
0
    #endif
3248
0
#endif /* !WOLFSSL_NO_ML_KEM */
3249
#ifdef WOLFSSL_MLKEM_KYBER
3250
        case WOLFSSL_KYBER_LEVEL1:
3251
        case WOLFSSL_KYBER_LEVEL3:
3252
        case WOLFSSL_KYBER_LEVEL5:
3253
    #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)
3254
        case WOLFSSL_P256_KYBER_LEVEL1:
3255
        case WOLFSSL_P384_KYBER_LEVEL3:
3256
        case WOLFSSL_P521_KYBER_LEVEL5:
3257
        case WOLFSSL_X25519_KYBER_LEVEL1:
3258
        case WOLFSSL_X448_KYBER_LEVEL3:
3259
        case WOLFSSL_X25519_KYBER_LEVEL3:
3260
        case WOLFSSL_P256_KYBER_LEVEL3:
3261
    #endif
3262
#endif /* WOLFSSL_MLKEM_KYBER */
3263
0
#endif
3264
0
            return 1;
3265
3266
0
        default:
3267
0
            return 0;
3268
0
    }
3269
0
}
3270
3271
int wolfSSL_UseSupportedCurve(WOLFSSL* ssl, word16 name)
3272
0
{
3273
0
    if (ssl == NULL || !isValidCurveGroup(name))
3274
0
        return BAD_FUNC_ARG;
3275
3276
0
    ssl->options.userCurves = 1;
3277
#if defined(NO_TLS)
3278
    return WOLFSSL_FAILURE;
3279
#else
3280
0
    return TLSX_UseSupportedCurve(&ssl->extensions, name, ssl->heap);
3281
0
#endif /* NO_TLS */
3282
0
}
3283
3284
3285
int wolfSSL_CTX_UseSupportedCurve(WOLFSSL_CTX* ctx, word16 name)
3286
0
{
3287
0
    if (ctx == NULL || !isValidCurveGroup(name))
3288
0
        return BAD_FUNC_ARG;
3289
3290
0
    ctx->userCurves = 1;
3291
#if defined(NO_TLS)
3292
    return WOLFSSL_FAILURE;
3293
#else
3294
0
    return TLSX_UseSupportedCurve(&ctx->extensions, name, ctx->heap);
3295
0
#endif /* NO_TLS */
3296
0
}
3297
3298
#if defined(OPENSSL_EXTRA)
3299
int  wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups,
3300
                                        int count)
3301
{
3302
    int i;
3303
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
3304
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
3305
    if (count == 0) {
3306
        WOLFSSL_MSG("Group count is zero");
3307
        return WOLFSSL_FAILURE;
3308
    }
3309
    if (count > WOLFSSL_MAX_GROUP_COUNT) {
3310
        WOLFSSL_MSG("Group count exceeds maximum");
3311
        return WOLFSSL_FAILURE;
3312
    }
3313
    for (i = 0; i < count; i++) {
3314
        if (isValidCurveGroup((word16)groups[i])) {
3315
            _groups[i] = groups[i];
3316
        }
3317
#ifdef HAVE_ECC
3318
        else {
3319
            /* groups may be populated with curve NIDs */
3320
            int oid = (int)nid2oid(groups[i], oidCurveType);
3321
            int name = (int)GetCurveByOID(oid);
3322
            if (name == 0) {
3323
                WOLFSSL_MSG("Invalid group name");
3324
                return WOLFSSL_FAILURE;
3325
            }
3326
            _groups[i] = name;
3327
        }
3328
#else
3329
        else {
3330
            WOLFSSL_MSG("Invalid group name");
3331
            return WOLFSSL_FAILURE;
3332
        }
3333
#endif
3334
    }
3335
    return wolfSSL_CTX_set_groups(ctx, _groups, count) == WOLFSSL_SUCCESS ?
3336
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3337
}
3338
3339
int  wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count)
3340
{
3341
    int i;
3342
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
3343
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
3344
    if (count == 0) {
3345
        WOLFSSL_MSG("Group count is zero");
3346
        return WOLFSSL_FAILURE;
3347
    }
3348
    if (count > WOLFSSL_MAX_GROUP_COUNT) {
3349
        WOLFSSL_MSG("Group count exceeds maximum");
3350
        return WOLFSSL_FAILURE;
3351
    }
3352
    for (i = 0; i < count; i++) {
3353
        if (isValidCurveGroup((word16)groups[i])) {
3354
            _groups[i] = groups[i];
3355
        }
3356
#ifdef HAVE_ECC
3357
        else {
3358
            /* groups may be populated with curve NIDs */
3359
            int oid = (int)nid2oid(groups[i], oidCurveType);
3360
            int name = (int)GetCurveByOID(oid);
3361
            if (name == 0) {
3362
                WOLFSSL_MSG("Invalid group name");
3363
                return WOLFSSL_FAILURE;
3364
            }
3365
            _groups[i] = name;
3366
        }
3367
#else
3368
        else {
3369
            WOLFSSL_MSG("Invalid group name");
3370
            return WOLFSSL_FAILURE;
3371
        }
3372
#endif
3373
    }
3374
    return wolfSSL_set_groups(ssl, _groups, count) == WOLFSSL_SUCCESS ?
3375
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3376
}
3377
#endif /* OPENSSL_EXTRA */
3378
#endif /* HAVE_SUPPORTED_CURVES */
3379
3380
/* Application-Layer Protocol Negotiation */
3381
#ifdef HAVE_ALPN
3382
3383
WOLFSSL_ABI
3384
int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list,
3385
                    word32 protocol_name_listSz, byte options)
3386
{
3387
    char    *list, *ptr = NULL, **token;
3388
    word16  len;
3389
    int     idx = 0;
3390
    int     ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
3391
3392
    WOLFSSL_ENTER("wolfSSL_UseALPN");
3393
3394
    if (ssl == NULL || protocol_name_list == NULL)
3395
        return BAD_FUNC_ARG;
3396
3397
    if (protocol_name_listSz > (WOLFSSL_MAX_ALPN_NUMBER *
3398
                                WOLFSSL_MAX_ALPN_PROTO_NAME_LEN +
3399
                                WOLFSSL_MAX_ALPN_NUMBER)) {
3400
        WOLFSSL_MSG("Invalid arguments, protocol name list too long");
3401
        return BAD_FUNC_ARG;
3402
    }
3403
3404
    if (!(options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) &&
3405
        !(options & WOLFSSL_ALPN_FAILED_ON_MISMATCH)) {
3406
            WOLFSSL_MSG("Invalid arguments, options not supported");
3407
            return BAD_FUNC_ARG;
3408
        }
3409
3410
3411
    list = (char *)XMALLOC(protocol_name_listSz+1, ssl->heap,
3412
                           DYNAMIC_TYPE_ALPN);
3413
    if (list == NULL) {
3414
        WOLFSSL_MSG("Memory failure");
3415
        return MEMORY_ERROR;
3416
    }
3417
3418
    token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1),
3419
        ssl->heap, DYNAMIC_TYPE_ALPN);
3420
    if (token == NULL) {
3421
        XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3422
        WOLFSSL_MSG("Memory failure");
3423
        return MEMORY_ERROR;
3424
    }
3425
    XMEMSET(token, 0, sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1));
3426
3427
    XSTRNCPY(list, protocol_name_list, protocol_name_listSz);
3428
    list[protocol_name_listSz] = '\0';
3429
3430
    /* read all protocol name from the list */
3431
    token[idx] = XSTRTOK(list, ",", &ptr);
3432
    while (idx < WOLFSSL_MAX_ALPN_NUMBER && token[idx] != NULL)
3433
        token[++idx] = XSTRTOK(NULL, ",", &ptr);
3434
3435
    /* add protocol name list in the TLS extension in reverse order */
3436
    while ((idx--) > 0) {
3437
        len = (word16)XSTRLEN(token[idx]);
3438
3439
        ret = TLSX_UseALPN(&ssl->extensions, token[idx], len, options,
3440
                                                                     ssl->heap);
3441
        if (ret != WOLFSSL_SUCCESS) {
3442
            WOLFSSL_MSG("TLSX_UseALPN failure");
3443
            break;
3444
        }
3445
    }
3446
3447
    XFREE(token, ssl->heap, DYNAMIC_TYPE_ALPN);
3448
    XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3449
3450
    return ret;
3451
}
3452
3453
int wolfSSL_ALPN_GetProtocol(WOLFSSL* ssl, char **protocol_name, word16 *size)
3454
{
3455
    return TLSX_ALPN_GetRequest(ssl ? ssl->extensions : NULL,
3456
                               (void **)protocol_name, size);
3457
}
3458
3459
int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, word16 *listSz)
3460
{
3461
    int i, len;
3462
    char *p;
3463
    byte *s;
3464
3465
    if (ssl == NULL || list == NULL || listSz == NULL)
3466
        return BAD_FUNC_ARG;
3467
3468
    if (ssl->alpn_peer_requested == NULL
3469
        || ssl->alpn_peer_requested_length == 0)
3470
        return BUFFER_ERROR;
3471
3472
    /* ssl->alpn_peer_requested are the original bytes sent in a ClientHello,
3473
     * formatted as (len-byte chars+)+. To turn n protocols into a
3474
     * comma-separated C string, one needs (n-1) commas and a final 0 byte
3475
     * which has the same length as the original.
3476
     * The returned length is the strlen() of the C string, so -1 of that. */
3477
    *listSz = ssl->alpn_peer_requested_length-1;
3478
    *list = p = (char *)XMALLOC(ssl->alpn_peer_requested_length, ssl->heap,
3479
                                DYNAMIC_TYPE_TLSX);
3480
    if (p == NULL)
3481
        return MEMORY_ERROR;
3482
3483
    for (i = 0, s = ssl->alpn_peer_requested;
3484
         i < ssl->alpn_peer_requested_length;
3485
         p += len, i += len)
3486
    {
3487
        if (i)
3488
            *p++ = ',';
3489
        len = s[i++];
3490
        /* guard against bad length bytes. */
3491
        if (i + len > ssl->alpn_peer_requested_length) {
3492
            XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
3493
            *list = NULL;
3494
            return WOLFSSL_FAILURE;
3495
        }
3496
        XMEMCPY(p, s + i, (size_t)len);
3497
    }
3498
    *p = 0;
3499
3500
    return WOLFSSL_SUCCESS;
3501
}
3502
3503
3504
/* used to free memory allocated by wolfSSL_ALPN_GetPeerProtocol */
3505
int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list)
3506
{
3507
    if (ssl == NULL) {
3508
        return BAD_FUNC_ARG;
3509
    }
3510
3511
    XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
3512
    *list = NULL;
3513
3514
    return WOLFSSL_SUCCESS;
3515
}
3516
3517
#endif /* HAVE_ALPN */
3518
3519
/* Secure Renegotiation */
3520
#ifdef HAVE_SERVER_RENEGOTIATION_INFO
3521
3522
/* user is forcing ability to use secure renegotiation, we discourage it */
3523
int wolfSSL_UseSecureRenegotiation(WOLFSSL* ssl)
3524
243
{
3525
243
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
3526
#if defined(NO_TLS)
3527
    (void)ssl;
3528
#else
3529
243
    if (ssl)
3530
243
        ret = TLSX_UseSecureRenegotiation(&ssl->extensions, ssl->heap);
3531
0
    else
3532
0
        ret = BAD_FUNC_ARG;
3533
3534
243
    if (ret == WOLFSSL_SUCCESS) {
3535
233
        TLSX* extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
3536
3537
233
        if (extension)
3538
233
            ssl->secure_renegotiation = (SecureRenegotiation*)extension->data;
3539
233
    }
3540
243
#endif /* !NO_TLS */
3541
243
    return ret;
3542
243
}
3543
3544
int wolfSSL_CTX_UseSecureRenegotiation(WOLFSSL_CTX* ctx)
3545
0
{
3546
0
    if (ctx == NULL)
3547
0
        return BAD_FUNC_ARG;
3548
3549
0
    ctx->useSecureReneg = 1;
3550
0
    return WOLFSSL_SUCCESS;
3551
0
}
3552
3553
#ifdef HAVE_SECURE_RENEGOTIATION
3554
/* do a secure renegotiation handshake, user forced, we discourage */
3555
static int _Rehandshake(WOLFSSL* ssl)
3556
{
3557
    int ret;
3558
3559
    if (ssl == NULL)
3560
        return BAD_FUNC_ARG;
3561
3562
    if (IsAtLeastTLSv1_3(ssl->version)) {
3563
        WOLFSSL_MSG("Secure Renegotiation not supported in TLS 1.3");
3564
        return SECURE_RENEGOTIATION_E;
3565
    }
3566
3567
    if (ssl->secure_renegotiation == NULL) {
3568
        WOLFSSL_MSG("Secure Renegotiation not forced on by user");
3569
        return SECURE_RENEGOTIATION_E;
3570
    }
3571
3572
    if (ssl->secure_renegotiation->enabled == 0) {
3573
        WOLFSSL_MSG("Secure Renegotiation not enabled at extension level");
3574
        return SECURE_RENEGOTIATION_E;
3575
    }
3576
3577
#ifdef WOLFSSL_DTLS
3578
    if (ssl->options.dtls && ssl->keys.dtls_epoch == 0xFFFF) {
3579
        WOLFSSL_MSG("Secure Renegotiation not allowed. Epoch would wrap");
3580
        return SECURE_RENEGOTIATION_E;
3581
    }
3582
#endif
3583
3584
    /* If the client started the renegotiation, the server will already
3585
     * have processed the client's hello. */
3586
    if (ssl->options.side != WOLFSSL_SERVER_END ||
3587
        ssl->options.acceptState != ACCEPT_FIRST_REPLY_DONE) {
3588
3589
        if (ssl->options.handShakeState != HANDSHAKE_DONE) {
3590
            if (!ssl->options.handShakeDone) {
3591
                WOLFSSL_MSG("Can't renegotiate until initial "
3592
                            "handshake complete");
3593
                return SECURE_RENEGOTIATION_E;
3594
            }
3595
            else {
3596
                WOLFSSL_MSG("Renegotiation already started. "
3597
                            "Moving it forward.");
3598
                ret = wolfSSL_negotiate(ssl);
3599
                if (ret == WOLFSSL_SUCCESS)
3600
                    ssl->secure_rene_count++;
3601
                return ret;
3602
            }
3603
        }
3604
3605
        /* reset handshake states */
3606
        ssl->options.sendVerify = 0;
3607
        ssl->options.serverState = NULL_STATE;
3608
        ssl->options.clientState = NULL_STATE;
3609
        ssl->options.connectState  = CONNECT_BEGIN;
3610
        ssl->options.acceptState   = ACCEPT_BEGIN_RENEG;
3611
        ssl->options.handShakeState = NULL_STATE;
3612
        ssl->options.processReply  = 0;  /* TODO, move states in internal.h */
3613
3614
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
3615
3616
        ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
3617
3618
#if !defined(NO_WOLFSSL_SERVER) && !defined(WOLFSSL_NO_TLS12)
3619
        if (ssl->options.side == WOLFSSL_SERVER_END) {
3620
            ret = SendHelloRequest(ssl);
3621
            if (ret != 0) {
3622
                ssl->error = ret;
3623
                return WOLFSSL_FATAL_ERROR;
3624
            }
3625
        }
3626
#endif /* !NO_WOLFSSL_SERVER && !WOLFSSL_NO_TLS12 */
3627
3628
        ret = InitHandshakeHashes(ssl);
3629
        if (ret != 0) {
3630
            ssl->error = ret;
3631
            return WOLFSSL_FATAL_ERROR;
3632
        }
3633
    }
3634
    ret = wolfSSL_negotiate(ssl);
3635
    if (ret == WOLFSSL_SUCCESS)
3636
        ssl->secure_rene_count++;
3637
    return ret;
3638
}
3639
3640
3641
/* do a secure renegotiation handshake, user forced, we discourage */
3642
int wolfSSL_Rehandshake(WOLFSSL* ssl)
3643
{
3644
    int ret;
3645
    WOLFSSL_ENTER("wolfSSL_Rehandshake");
3646
3647
    if (ssl == NULL)
3648
        return WOLFSSL_FAILURE;
3649
3650
#ifdef HAVE_SESSION_TICKET
3651
    ret = WOLFSSL_SUCCESS;
3652
#endif
3653
3654
    if (ssl->options.side == WOLFSSL_SERVER_END) {
3655
        /* Reset option to send certificate verify. */
3656
        ssl->options.sendVerify = 0;
3657
        /* Reset resuming flag to do full secure handshake. */
3658
        ssl->options.resuming = 0;
3659
    }
3660
    else {
3661
        /* Reset resuming flag to do full secure handshake. */
3662
        ssl->options.resuming = 0;
3663
        #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_CLIENT)
3664
            /* Clearing the ticket. */
3665
            ret = wolfSSL_UseSessionTicket(ssl);
3666
        #endif
3667
    }
3668
    /* CLIENT/SERVER: Reset peer authentication for full secure handshake. */
3669
    ssl->options.peerAuthGood = 0;
3670
3671
#ifdef HAVE_SESSION_TICKET
3672
    if (ret == WOLFSSL_SUCCESS)
3673
#endif
3674
        ret = _Rehandshake(ssl);
3675
3676
    return ret;
3677
}
3678
3679
3680
#ifndef NO_WOLFSSL_CLIENT
3681
3682
/* do a secure resumption handshake, user forced, we discourage */
3683
int wolfSSL_SecureResume(WOLFSSL* ssl)
3684
{
3685
    WOLFSSL_ENTER("wolfSSL_SecureResume");
3686
3687
    if (ssl == NULL)
3688
        return BAD_FUNC_ARG;
3689
3690
    if (ssl->options.side == WOLFSSL_SERVER_END) {
3691
        ssl->error = SIDE_ERROR;
3692
        return WOLFSSL_FATAL_ERROR;
3693
    }
3694
3695
    return _Rehandshake(ssl);
3696
}
3697
3698
#endif /* NO_WOLFSSL_CLIENT */
3699
3700
#endif /* HAVE_SECURE_RENEGOTIATION */
3701
3702
long wolfSSL_SSL_get_secure_renegotiation_support(WOLFSSL* ssl)
3703
0
{
3704
0
    WOLFSSL_ENTER("wolfSSL_SSL_get_secure_renegotiation_support");
3705
3706
0
    if (!ssl || !ssl->secure_renegotiation)
3707
0
        return WOLFSSL_FAILURE;
3708
0
    return ssl->secure_renegotiation->enabled;
3709
0
}
3710
3711
#endif /* HAVE_SECURE_RENEGOTIATION_INFO */
3712
3713
#if !defined(NO_WOLFSSL_CLIENT) && !defined(WOLFSSL_NO_TLS12) && \
3714
    defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)
3715
WOLFSSL_API int wolfSSL_get_scr_check_enabled(const WOLFSSL* ssl)
3716
{
3717
    WOLFSSL_ENTER("wolfSSL_get_scr_check_enabled");
3718
3719
    if (ssl == NULL)
3720
        return BAD_FUNC_ARG;
3721
3722
    return ssl->scr_check_enabled;
3723
}
3724
3725
WOLFSSL_API int wolfSSL_set_scr_check_enabled(WOLFSSL* ssl, byte enabled)
3726
{
3727
    WOLFSSL_ENTER("wolfSSL_set_scr_check_enabled");
3728
3729
    if (ssl == NULL)
3730
        return BAD_FUNC_ARG;
3731
3732
    ssl->scr_check_enabled = !!enabled;
3733
    return WOLFSSL_SUCCESS;
3734
}
3735
#endif
3736
3737
#if defined(HAVE_SESSION_TICKET)
3738
/* Session Ticket */
3739
3740
#if !defined(NO_WOLFSSL_SERVER)
3741
int wolfSSL_CTX_NoTicketTLSv12(WOLFSSL_CTX* ctx)
3742
{
3743
    if (ctx == NULL)
3744
        return BAD_FUNC_ARG;
3745
3746
    ctx->noTicketTls12 = 1;
3747
3748
    return WOLFSSL_SUCCESS;
3749
}
3750
3751
int wolfSSL_NoTicketTLSv12(WOLFSSL* ssl)
3752
{
3753
    if (ssl == NULL)
3754
        return BAD_FUNC_ARG;
3755
3756
    ssl->options.noTicketTls12 = 1;
3757
3758
    return WOLFSSL_SUCCESS;
3759
}
3760
3761
/* WOLFSSL_SUCCESS on ok */
3762
int wolfSSL_CTX_set_TicketEncCb(WOLFSSL_CTX* ctx, SessionTicketEncCb cb)
3763
{
3764
    if (ctx == NULL)
3765
        return BAD_FUNC_ARG;
3766
3767
    ctx->ticketEncCb = cb;
3768
3769
    return WOLFSSL_SUCCESS;
3770
}
3771
3772
/* set hint interval, WOLFSSL_SUCCESS on ok */
3773
int wolfSSL_CTX_set_TicketHint(WOLFSSL_CTX* ctx, int hint)
3774
{
3775
    if (ctx == NULL)
3776
        return BAD_FUNC_ARG;
3777
3778
    /* RFC8446 Section 4.6.1: Servers MUST NOT use any value greater than
3779
     * 604800 seconds (7 days). */
3780
    if (hint < 0 || hint > 604800)
3781
        return BAD_FUNC_ARG;
3782
3783
    ctx->ticketHint = hint;
3784
3785
    return WOLFSSL_SUCCESS;
3786
}
3787
3788
/* set user context, WOLFSSL_SUCCESS on ok */
3789
int wolfSSL_CTX_set_TicketEncCtx(WOLFSSL_CTX* ctx, void* userCtx)
3790
{
3791
    if (ctx == NULL)
3792
        return BAD_FUNC_ARG;
3793
3794
    ctx->ticketEncCtx = userCtx;
3795
3796
    return WOLFSSL_SUCCESS;
3797
}
3798
3799
/* get user context - returns userCtx on success, NULL on failure */
3800
void* wolfSSL_CTX_get_TicketEncCtx(WOLFSSL_CTX* ctx)
3801
{
3802
    if (ctx == NULL)
3803
        return NULL;
3804
3805
    return ctx->ticketEncCtx;
3806
}
3807
3808
#ifdef WOLFSSL_TLS13
3809
/* set the maximum number of tickets to send
3810
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on fail
3811
 */
3812
int wolfSSL_CTX_set_num_tickets(WOLFSSL_CTX* ctx, size_t mxTickets)
3813
{
3814
    if (ctx == NULL)
3815
        return WOLFSSL_FAILURE;
3816
3817
    ctx->maxTicketTls13 = (unsigned int)mxTickets;
3818
    return WOLFSSL_SUCCESS;
3819
}
3820
3821
/* get the maximum number of tickets to send
3822
 * return number of tickets set to be sent
3823
 */
3824
size_t wolfSSL_CTX_get_num_tickets(WOLFSSL_CTX* ctx)
3825
{
3826
    if (ctx == NULL)
3827
        return 0;
3828
3829
    return (size_t)ctx->maxTicketTls13;
3830
}
3831
#endif /* WOLFSSL_TLS13 */
3832
#endif /* !NO_WOLFSSL_SERVER */
3833
3834
#if !defined(NO_WOLFSSL_CLIENT)
3835
int wolfSSL_UseSessionTicket(WOLFSSL* ssl)
3836
{
3837
    if (ssl == NULL)
3838
        return BAD_FUNC_ARG;
3839
3840
    return TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
3841
}
3842
3843
int wolfSSL_CTX_UseSessionTicket(WOLFSSL_CTX* ctx)
3844
{
3845
    if (ctx == NULL)
3846
        return BAD_FUNC_ARG;
3847
3848
    return TLSX_UseSessionTicket(&ctx->extensions, NULL, ctx->heap);
3849
}
3850
3851
int wolfSSL_get_SessionTicket(WOLFSSL* ssl, byte* buf, word32* bufSz)
3852
{
3853
    if (ssl == NULL || bufSz == NULL)
3854
        return BAD_FUNC_ARG;
3855
3856
    if (*bufSz == 0 && buf == NULL) {
3857
        *bufSz = ssl->session->ticketLen;
3858
        return LENGTH_ONLY_E;
3859
    }
3860
3861
    if (buf == NULL)
3862
        return BAD_FUNC_ARG;
3863
3864
    if (ssl->session->ticketLen <= *bufSz) {
3865
        XMEMCPY(buf, ssl->session->ticket, ssl->session->ticketLen);
3866
        *bufSz = ssl->session->ticketLen;
3867
    }
3868
    else
3869
        *bufSz = 0;
3870
3871
    return WOLFSSL_SUCCESS;
3872
}
3873
3874
int wolfSSL_set_SessionTicket(WOLFSSL* ssl, const byte* buf,
3875
                                          word32 bufSz)
3876
{
3877
    if (ssl == NULL || (buf == NULL && bufSz > 0))
3878
        return BAD_FUNC_ARG;
3879
3880
    if (bufSz > 0) {
3881
        /* Ticket will fit into static ticket */
3882
        if (bufSz <= SESSION_TICKET_LEN) {
3883
            if (ssl->session->ticketLenAlloc > 0) {
3884
                XFREE(ssl->session->ticket, ssl->session->heap,
3885
                      DYNAMIC_TYPE_SESSION_TICK);
3886
                ssl->session->ticketLenAlloc = 0;
3887
                ssl->session->ticket = ssl->session->staticTicket;
3888
            }
3889
        }
3890
        else { /* Ticket requires dynamic ticket storage */
3891
            /* is dyn buffer big enough */
3892
            if (ssl->session->ticketLen < bufSz) {
3893
                if (ssl->session->ticketLenAlloc > 0) {
3894
                    XFREE(ssl->session->ticket, ssl->session->heap,
3895
                          DYNAMIC_TYPE_SESSION_TICK);
3896
                }
3897
                ssl->session->ticket = (byte*)XMALLOC(bufSz, ssl->session->heap,
3898
                        DYNAMIC_TYPE_SESSION_TICK);
3899
                if(ssl->session->ticket == NULL) {
3900
                    ssl->session->ticket = ssl->session->staticTicket;
3901
                    ssl->session->ticketLenAlloc = 0;
3902
                    return MEMORY_ERROR;
3903
                }
3904
                ssl->session->ticketLenAlloc = (word16)bufSz;
3905
            }
3906
        }
3907
        XMEMCPY(ssl->session->ticket, buf, bufSz);
3908
    }
3909
    ssl->session->ticketLen = (word16)bufSz;
3910
3911
    return WOLFSSL_SUCCESS;
3912
}
3913
3914
3915
int wolfSSL_set_SessionTicket_cb(WOLFSSL* ssl,
3916
                                 CallbackSessionTicket cb, void* ctx)
3917
{
3918
    if (ssl == NULL)
3919
        return BAD_FUNC_ARG;
3920
3921
    ssl->session_ticket_cb = cb;
3922
    ssl->session_ticket_ctx = ctx;
3923
3924
    return WOLFSSL_SUCCESS;
3925
}
3926
#endif /* !NO_WOLFSSL_CLIENT */
3927
3928
#endif /* HAVE_SESSION_TICKET */
3929
3930
3931
#ifdef HAVE_EXTENDED_MASTER
3932
#ifndef NO_WOLFSSL_CLIENT
3933
3934
int wolfSSL_CTX_DisableExtendedMasterSecret(WOLFSSL_CTX* ctx)
3935
0
{
3936
0
    if (ctx == NULL)
3937
0
        return BAD_FUNC_ARG;
3938
3939
0
    ctx->haveEMS = 0;
3940
3941
0
    return WOLFSSL_SUCCESS;
3942
0
}
3943
3944
3945
int wolfSSL_DisableExtendedMasterSecret(WOLFSSL* ssl)
3946
0
{
3947
0
    if (ssl == NULL)
3948
0
        return BAD_FUNC_ARG;
3949
3950
0
    ssl->options.haveEMS = 0;
3951
3952
0
    return WOLFSSL_SUCCESS;
3953
0
}
3954
3955
#endif
3956
#endif
3957
3958
3959
#ifndef WOLFSSL_LEANPSK
3960
3961
int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags)
3962
0
{
3963
0
    int ret;
3964
0
    int oldFlags;
3965
3966
0
    WOLFSSL_ENTER("wolfSSL_send");
3967
3968
0
    if (ssl == NULL || data == NULL || sz < 0)
3969
0
        return BAD_FUNC_ARG;
3970
3971
0
    oldFlags = ssl->wflags;
3972
3973
0
    ssl->wflags = flags;
3974
0
    ret = wolfSSL_write(ssl, data, sz);
3975
0
    ssl->wflags = oldFlags;
3976
3977
0
    WOLFSSL_LEAVE("wolfSSL_send", ret);
3978
3979
0
    return ret;
3980
0
}
3981
3982
3983
int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags)
3984
0
{
3985
0
    int ret;
3986
0
    int oldFlags;
3987
3988
0
    WOLFSSL_ENTER("wolfSSL_recv");
3989
3990
0
    if (ssl == NULL || data == NULL || sz < 0)
3991
0
        return BAD_FUNC_ARG;
3992
3993
0
    oldFlags = ssl->rflags;
3994
3995
0
    ssl->rflags = flags;
3996
0
    ret = wolfSSL_read(ssl, data, sz);
3997
0
    ssl->rflags = oldFlags;
3998
3999
0
    WOLFSSL_LEAVE("wolfSSL_recv", ret);
4000
4001
0
    return ret;
4002
0
}
4003
#endif
4004
4005
int wolfSSL_SendUserCanceled(WOLFSSL* ssl)
4006
0
{
4007
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
4008
0
    WOLFSSL_ENTER("wolfSSL_recv");
4009
4010
0
    if (ssl != NULL) {
4011
0
        ssl->error = SendAlert(ssl, alert_warning, user_canceled);
4012
0
        if (ssl->error < 0) {
4013
0
            WOLFSSL_ERROR(ssl->error);
4014
0
        }
4015
0
        else {
4016
0
            ret = wolfSSL_shutdown(ssl);
4017
0
        }
4018
0
    }
4019
4020
0
    WOLFSSL_LEAVE("wolfSSL_SendUserCanceled", ret);
4021
4022
0
    return ret;
4023
0
}
4024
4025
/* WOLFSSL_SUCCESS on ok */
4026
WOLFSSL_ABI
4027
int wolfSSL_shutdown(WOLFSSL* ssl)
4028
0
{
4029
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
4030
0
    WOLFSSL_ENTER("wolfSSL_shutdown");
4031
4032
0
    if (ssl == NULL)
4033
0
        return WOLFSSL_FATAL_ERROR;
4034
4035
0
    if (ssl->options.quietShutdown) {
4036
0
        WOLFSSL_MSG("quiet shutdown, no close notify sent");
4037
0
        ret = WOLFSSL_SUCCESS;
4038
0
    }
4039
0
    else {
4040
4041
        /* Try to flush the buffer first, it might contain the alert */
4042
0
        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE) &&
4043
0
            ssl->buffers.outputBuffer.length > 0) {
4044
0
            ret = SendBuffered(ssl);
4045
0
            if (ret != 0) {
4046
0
                ssl->error = ret;
4047
                /* for error tracing */
4048
0
                if (ret != WC_NO_ERR_TRACE(WANT_WRITE))
4049
0
                    WOLFSSL_ERROR(ret);
4050
0
                ret = WOLFSSL_FATAL_ERROR;
4051
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4052
0
                return ret;
4053
0
            }
4054
4055
0
            ssl->error = WOLFSSL_ERROR_NONE;
4056
            /* we succeeded in sending the alert now */
4057
0
            if (ssl->options.sentNotify)  {
4058
                /* just after we send the alert, if we didn't receive the alert
4059
                 * from the other peer yet, return WOLFSSL_STHUDOWN_NOT_DONE */
4060
0
                if (!ssl->options.closeNotify) {
4061
0
                    ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4062
0
                    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4063
0
                    return ret;
4064
0
                }
4065
0
                else {
4066
0
                    ssl->options.shutdownDone = 1;
4067
0
                    ret = WOLFSSL_SUCCESS;
4068
0
                }
4069
0
            }
4070
0
        }
4071
4072
        /* try to send close notify, not an error if can't */
4073
0
        if (!ssl->options.isClosed && !ssl->options.connReset &&
4074
0
                                      !ssl->options.sentNotify) {
4075
0
            ssl->error = SendAlert(ssl, alert_warning, close_notify);
4076
4077
            /* the alert is now sent or sitting in the buffer,
4078
             * where will be sent eventually */
4079
0
            if (ssl->error == 0 || ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4080
0
                ssl->options.sentNotify = 1;
4081
4082
0
            if (ssl->error < 0) {
4083
0
                WOLFSSL_ERROR(ssl->error);
4084
0
                return WOLFSSL_FATAL_ERROR;
4085
0
            }
4086
4087
0
            if (ssl->options.closeNotify) {
4088
0
                ret = WOLFSSL_SUCCESS;
4089
0
                ssl->options.shutdownDone = 1;
4090
0
            }
4091
0
            else {
4092
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4093
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4094
0
                return ret;
4095
0
            }
4096
0
        }
4097
4098
#ifdef WOLFSSL_SHUTDOWNONCE
4099
        if (ssl->options.isClosed || ssl->options.connReset) {
4100
            /* Shutdown has already occurred.
4101
             * Caller is free to ignore this error. */
4102
            return SSL_SHUTDOWN_ALREADY_DONE_E;
4103
        }
4104
#endif
4105
4106
        /* wolfSSL_shutdown called again for bidirectional shutdown */
4107
0
        if (ssl->options.sentNotify && !ssl->options.closeNotify) {
4108
0
            ret = ProcessReply(ssl);
4109
0
            if ((ret == WC_NO_ERR_TRACE(ZERO_RETURN)) ||
4110
0
                (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))) {
4111
                /* simulate OpenSSL behavior */
4112
0
                ssl->options.shutdownDone = 1;
4113
                /* Clear error */
4114
0
                ssl->error = WOLFSSL_ERROR_NONE;
4115
0
                ret = WOLFSSL_SUCCESS;
4116
0
            }
4117
0
            else if (ret == WC_NO_ERR_TRACE(MEMORY_E)) {
4118
0
                ret = WOLFSSL_FATAL_ERROR;
4119
0
            }
4120
0
            else if (ret == WC_NO_ERR_TRACE(WANT_READ)) {
4121
0
                ssl->error = ret;
4122
0
                ret = WOLFSSL_FATAL_ERROR;
4123
0
            }
4124
0
            else if (ssl->error == WOLFSSL_ERROR_NONE) {
4125
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4126
0
            }
4127
0
            else {
4128
0
                WOLFSSL_ERROR(ssl->error);
4129
0
                ret = WOLFSSL_FATAL_ERROR;
4130
0
            }
4131
0
        }
4132
0
    }
4133
4134
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
4135
    /* reset WOLFSSL structure state for possible reuse */
4136
    if (ret == WOLFSSL_SUCCESS) {
4137
        if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) {
4138
            WOLFSSL_MSG("could not clear WOLFSSL");
4139
            ret = WOLFSSL_FATAL_ERROR;
4140
        }
4141
    }
4142
#endif
4143
4144
0
    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4145
4146
0
    return ret;
4147
0
}
4148
#endif /* !NO_TLS */
4149
4150
/* get current error state value */
4151
int wolfSSL_state(WOLFSSL* ssl)
4152
0
{
4153
0
    if (ssl == NULL) {
4154
0
        return BAD_FUNC_ARG;
4155
0
    }
4156
4157
0
    return ssl->error;
4158
0
}
4159
4160
4161
WOLFSSL_ABI
4162
int wolfSSL_get_error(WOLFSSL* ssl, int ret)
4163
0
{
4164
0
    WOLFSSL_ENTER("wolfSSL_get_error");
4165
4166
0
    if (ret > 0)
4167
0
        return WOLFSSL_ERROR_NONE;
4168
0
    if (ssl == NULL)
4169
0
        return BAD_FUNC_ARG;
4170
4171
0
    WOLFSSL_LEAVE("wolfSSL_get_error", ssl->error);
4172
4173
    /* make sure converted types are handled in SetErrorString() too */
4174
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4175
0
        return WOLFSSL_ERROR_WANT_READ;         /* convert to OpenSSL type */
4176
0
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4177
0
        return WOLFSSL_ERROR_WANT_WRITE;        /* convert to OpenSSL type */
4178
0
    else if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) ||
4179
0
             ssl->options.shutdownDone)
4180
0
        return WOLFSSL_ERROR_ZERO_RETURN;       /* convert to OpenSSL type */
4181
#ifdef OPENSSL_EXTRA
4182
    else if (ssl->error == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
4183
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
4184
    else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E))
4185
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
4186
#endif
4187
#ifdef WOLFSSL_ASYNC_CRYPT
4188
    else if (ssl->error == WC_NO_ERR_TRACE(MP_WOULDBLOCK))
4189
        return WC_PENDING_E;                    /* map non-blocking crypto */
4190
#endif
4191
0
    return ssl->error;
4192
0
}
4193
4194
4195
/* retrieve alert history, WOLFSSL_SUCCESS on ok */
4196
int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
4197
0
{
4198
0
    if (ssl && h) {
4199
0
        *h = ssl->alert_history;
4200
0
    }
4201
0
    return WOLFSSL_SUCCESS;
4202
0
}
4203
4204
#ifdef OPENSSL_EXTRA
4205
/* returns SSL_WRITING, SSL_READING or SSL_NOTHING */
4206
int wolfSSL_want(WOLFSSL* ssl)
4207
{
4208
    int rw_state = WOLFSSL_NOTHING;
4209
    if (ssl) {
4210
        if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4211
            rw_state = WOLFSSL_READING;
4212
        else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4213
            rw_state = WOLFSSL_WRITING;
4214
    }
4215
    return rw_state;
4216
}
4217
#endif
4218
4219
/* return TRUE if current error is want read */
4220
int wolfSSL_want_read(WOLFSSL* ssl)
4221
0
{
4222
0
    WOLFSSL_ENTER("wolfSSL_want_read");
4223
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4224
0
        return 1;
4225
4226
0
    return 0;
4227
0
}
4228
4229
/* return TRUE if current error is want write */
4230
int wolfSSL_want_write(WOLFSSL* ssl)
4231
0
{
4232
0
    WOLFSSL_ENTER("wolfSSL_want_write");
4233
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4234
0
        return 1;
4235
4236
0
    return 0;
4237
0
}
4238
4239
char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data)
4240
0
{
4241
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string");
4242
0
    if (data) {
4243
0
        SetErrorString((int)errNumber, data);
4244
0
        return data;
4245
0
    }
4246
0
    else {
4247
0
        static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0};
4248
0
        SetErrorString((int)errNumber, tmp);
4249
0
        return tmp;
4250
0
    }
4251
0
}
4252
4253
4254
void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
4255
0
{
4256
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string_n");
4257
0
    if (len >= WOLFSSL_MAX_ERROR_SZ)
4258
0
        wolfSSL_ERR_error_string(e, buf);
4259
0
    else {
4260
0
        WOLFSSL_MSG("Error buffer too short, truncating");
4261
0
        if (len) {
4262
0
            char tmp[WOLFSSL_MAX_ERROR_SZ];
4263
0
            wolfSSL_ERR_error_string(e, tmp);
4264
0
            XMEMCPY(buf, tmp, len-1);
4265
0
            buf[len-1] = '\0';
4266
0
        }
4267
0
    }
4268
0
}
4269
4270
4271
/* don't free temporary arrays at end of handshake */
4272
void wolfSSL_KeepArrays(WOLFSSL* ssl)
4273
0
{
4274
0
    if (ssl)
4275
0
        ssl->options.saveArrays = 1;
4276
0
}
4277
4278
4279
/* user doesn't need temporary arrays anymore, Free */
4280
void wolfSSL_FreeArrays(WOLFSSL* ssl)
4281
0
{
4282
0
    if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
4283
0
        ssl->options.saveArrays = 0;
4284
0
        FreeArrays(ssl, 1);
4285
0
    }
4286
0
}
4287
4288
/* Set option to indicate that the resources are not to be freed after
4289
 * handshake.
4290
 *
4291
 * ssl  The SSL/TLS object.
4292
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4293
 */
4294
int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
4295
0
{
4296
0
    if (ssl == NULL)
4297
0
        return BAD_FUNC_ARG;
4298
4299
0
    ssl->options.keepResources = 1;
4300
4301
0
    return 0;
4302
0
}
4303
4304
/* Free the handshake resources after handshake.
4305
 *
4306
 * ssl  The SSL/TLS object.
4307
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4308
 */
4309
int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
4310
0
{
4311
0
    if (ssl == NULL)
4312
0
        return BAD_FUNC_ARG;
4313
4314
0
    FreeHandshakeResources(ssl);
4315
4316
0
    return 0;
4317
0
}
4318
4319
/* Use the client's order of preference when matching cipher suites.
4320
 *
4321
 * ssl  The SSL/TLS context object.
4322
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4323
 */
4324
int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
4325
0
{
4326
0
    if (ctx == NULL)
4327
0
        return BAD_FUNC_ARG;
4328
4329
0
    ctx->useClientOrder = 1;
4330
4331
0
    return 0;
4332
0
}
4333
4334
/* Use the client's order of preference when matching cipher suites.
4335
 *
4336
 * ssl  The SSL/TLS object.
4337
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4338
 */
4339
int wolfSSL_UseClientSuites(WOLFSSL* ssl)
4340
0
{
4341
0
    if (ssl == NULL)
4342
0
        return BAD_FUNC_ARG;
4343
4344
0
    ssl->options.useClientOrder = 1;
4345
4346
0
    return 0;
4347
0
}
4348
4349
#ifdef WOLFSSL_DTLS
4350
const byte* wolfSSL_GetDtlsMacSecret(WOLFSSL* ssl, int verify, int epochOrder)
4351
{
4352
#ifndef WOLFSSL_AEAD_ONLY
4353
    Keys* keys = NULL;
4354
4355
    (void)epochOrder;
4356
4357
    if (ssl == NULL)
4358
        return NULL;
4359
4360
#ifdef HAVE_SECURE_RENEGOTIATION
4361
    switch (epochOrder) {
4362
    case PEER_ORDER:
4363
        if (IsDtlsMsgSCRKeys(ssl))
4364
            keys = &ssl->secure_renegotiation->tmp_keys;
4365
        else
4366
            keys = &ssl->keys;
4367
        break;
4368
    case PREV_ORDER:
4369
        keys = &ssl->keys;
4370
        break;
4371
    case CUR_ORDER:
4372
        if (DtlsUseSCRKeys(ssl))
4373
            keys = &ssl->secure_renegotiation->tmp_keys;
4374
        else
4375
            keys = &ssl->keys;
4376
        break;
4377
    default:
4378
        WOLFSSL_MSG("Unknown epoch order");
4379
        return NULL;
4380
    }
4381
#else
4382
    keys = &ssl->keys;
4383
#endif
4384
4385
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
4386
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
4387
        return keys->client_write_MAC_secret;
4388
    else
4389
        return keys->server_write_MAC_secret;
4390
#else
4391
    (void)ssl;
4392
    (void)verify;
4393
    (void)epochOrder;
4394
4395
    return NULL;
4396
#endif
4397
}
4398
#endif /* WOLFSSL_DTLS */
4399
4400
const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
4401
946
{
4402
946
#ifndef WOLFSSL_AEAD_ONLY
4403
946
    if (ssl == NULL)
4404
0
        return NULL;
4405
4406
946
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
4407
162
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
4408
823
        return ssl->keys.client_write_MAC_secret;
4409
123
    else
4410
123
        return ssl->keys.server_write_MAC_secret;
4411
#else
4412
    (void)ssl;
4413
    (void)verify;
4414
4415
    return NULL;
4416
#endif
4417
946
}
4418
4419
int wolfSSL_GetSide(WOLFSSL* ssl)
4420
0
{
4421
0
    if (ssl)
4422
0
        return ssl->options.side;
4423
4424
0
    return BAD_FUNC_ARG;
4425
0
}
4426
4427
#ifdef ATOMIC_USER
4428
4429
void  wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
4430
{
4431
    if (ctx)
4432
        ctx->MacEncryptCb = cb;
4433
}
4434
4435
4436
void  wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
4437
{
4438
    if (ssl)
4439
        ssl->MacEncryptCtx = ctx;
4440
}
4441
4442
4443
void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
4444
{
4445
    if (ssl)
4446
        return ssl->MacEncryptCtx;
4447
4448
    return NULL;
4449
}
4450
4451
4452
void  wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
4453
{
4454
    if (ctx)
4455
        ctx->DecryptVerifyCb = cb;
4456
}
4457
4458
4459
void  wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
4460
{
4461
    if (ssl)
4462
        ssl->DecryptVerifyCtx = ctx;
4463
}
4464
4465
4466
void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
4467
{
4468
    if (ssl)
4469
        return ssl->DecryptVerifyCtx;
4470
4471
    return NULL;
4472
}
4473
4474
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
4475
/**
4476
 * Set the callback, against the context, that encrypts then MACs.
4477
 *
4478
 * ctx  SSL/TLS context.
4479
 * cb   Callback function to use with Encrypt-Then-MAC.
4480
 */
4481
void  wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
4482
{
4483
    if (ctx)
4484
        ctx->EncryptMacCb = cb;
4485
}
4486
4487
/**
4488
 * Set the context to use with callback that encrypts then MACs.
4489
 *
4490
 * ssl  SSL/TLS object.
4491
 * ctx  Callback function's context.
4492
 */
4493
void  wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
4494
{
4495
    if (ssl)
4496
        ssl->EncryptMacCtx = ctx;
4497
}
4498
4499
/**
4500
 * Get the context being used with callback that encrypts then MACs.
4501
 *
4502
 * ssl  SSL/TLS object.
4503
 * returns callback function's context or NULL if SSL/TLS object is NULL.
4504
 */
4505
void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
4506
{
4507
    if (ssl)
4508
        return ssl->EncryptMacCtx;
4509
4510
    return NULL;
4511
}
4512
4513
4514
/**
4515
 * Set the callback, against the context, that MAC verifies then decrypts.
4516
 *
4517
 * ctx  SSL/TLS context.
4518
 * cb   Callback function to use with Encrypt-Then-MAC.
4519
 */
4520
void  wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
4521
{
4522
    if (ctx)
4523
        ctx->VerifyDecryptCb = cb;
4524
}
4525
4526
/**
4527
 * Set the context to use with callback that MAC verifies then decrypts.
4528
 *
4529
 * ssl  SSL/TLS object.
4530
 * ctx  Callback function's context.
4531
 */
4532
void  wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
4533
{
4534
    if (ssl)
4535
        ssl->VerifyDecryptCtx = ctx;
4536
}
4537
4538
/**
4539
 * Get the context being used with callback that MAC verifies then decrypts.
4540
 *
4541
 * ssl  SSL/TLS object.
4542
 * returns callback function's context or NULL if SSL/TLS object is NULL.
4543
 */
4544
void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
4545
{
4546
    if (ssl)
4547
        return ssl->VerifyDecryptCtx;
4548
4549
    return NULL;
4550
}
4551
#endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
4552
4553
4554
4555
const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
4556
{
4557
    if (ssl)
4558
        return ssl->keys.client_write_key;
4559
4560
    return NULL;
4561
}
4562
4563
4564
const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
4565
{
4566
    if (ssl)
4567
        return ssl->keys.client_write_IV;
4568
4569
    return NULL;
4570
}
4571
4572
4573
const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
4574
{
4575
    if (ssl)
4576
        return ssl->keys.server_write_key;
4577
4578
    return NULL;
4579
}
4580
4581
4582
const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
4583
{
4584
    if (ssl)
4585
        return ssl->keys.server_write_IV;
4586
4587
    return NULL;
4588
}
4589
4590
int wolfSSL_GetKeySize(WOLFSSL* ssl)
4591
{
4592
    if (ssl)
4593
        return ssl->specs.key_size;
4594
4595
    return BAD_FUNC_ARG;
4596
}
4597
4598
4599
int wolfSSL_GetIVSize(WOLFSSL* ssl)
4600
{
4601
    if (ssl)
4602
        return ssl->specs.iv_size;
4603
4604
    return BAD_FUNC_ARG;
4605
}
4606
4607
4608
int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
4609
{
4610
    if (ssl)
4611
        return ssl->specs.bulk_cipher_algorithm;
4612
4613
    return BAD_FUNC_ARG;
4614
}
4615
4616
4617
int wolfSSL_GetCipherType(WOLFSSL* ssl)
4618
{
4619
    if (ssl == NULL)
4620
        return BAD_FUNC_ARG;
4621
4622
#ifndef WOLFSSL_AEAD_ONLY
4623
    if (ssl->specs.cipher_type == block)
4624
        return WOLFSSL_BLOCK_TYPE;
4625
    if (ssl->specs.cipher_type == stream)
4626
        return WOLFSSL_STREAM_TYPE;
4627
#endif
4628
    if (ssl->specs.cipher_type == aead)
4629
        return WOLFSSL_AEAD_TYPE;
4630
4631
    return WOLFSSL_FATAL_ERROR;
4632
}
4633
4634
4635
int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
4636
{
4637
    if (ssl == NULL)
4638
        return BAD_FUNC_ARG;
4639
4640
    return ssl->specs.block_size;
4641
}
4642
4643
4644
int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
4645
{
4646
    if (ssl == NULL)
4647
        return BAD_FUNC_ARG;
4648
4649
    return ssl->specs.aead_mac_size;
4650
}
4651
4652
4653
int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
4654
{
4655
    if (ssl == NULL)
4656
        return BAD_FUNC_ARG;
4657
4658
    if (ssl->options.tls1_1)
4659
        return 1;
4660
4661
    return 0;
4662
}
4663
4664
4665
4666
int wolfSSL_GetHmacSize(WOLFSSL* ssl)
4667
{
4668
    /* AEAD ciphers don't have HMAC keys */
4669
    if (ssl)
4670
        return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
4671
4672
    return BAD_FUNC_ARG;
4673
}
4674
4675
#ifdef WORD64_AVAILABLE
4676
int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
4677
{
4678
    if ((ssl == NULL) || (seq == NULL))
4679
        return BAD_FUNC_ARG;
4680
4681
    *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
4682
                    ssl->keys.peer_sequence_number_lo;
4683
    return !(*seq);
4684
}
4685
4686
int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
4687
{
4688
    if ((ssl == NULL) || (seq == NULL))
4689
        return BAD_FUNC_ARG;
4690
4691
    *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
4692
                    ssl->keys.sequence_number_lo;
4693
    return !(*seq);
4694
}
4695
#endif
4696
4697
#endif /* ATOMIC_USER */
4698
4699
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) \
4700
    && defined(XFPRINTF)
4701
4702
void wolfSSL_ERR_print_errors_fp(XFILE fp, int err)
4703
0
{
4704
0
    char data[WOLFSSL_MAX_ERROR_SZ + 1];
4705
4706
0
    WOLFSSL_ENTER("wolfSSL_ERR_print_errors_fp");
4707
0
    SetErrorString(err, data);
4708
0
    if (XFPRINTF(fp, "%s", data) < 0)
4709
0
        WOLFSSL_MSG("fprintf failed in wolfSSL_ERR_print_errors_fp");
4710
0
}
4711
4712
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
4713
void wolfSSL_ERR_dump_errors_fp(XFILE fp)
4714
{
4715
    wc_ERR_print_errors_fp(fp);
4716
}
4717
4718
void wolfSSL_ERR_print_errors_cb (int (*cb)(const char *str, size_t len,
4719
                                            void *u), void *u)
4720
{
4721
    wc_ERR_print_errors_cb(cb, u);
4722
}
4723
#endif
4724
#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM && XFPRINTF */
4725
4726
/*
4727
 * TODO This ssl parameter needs to be changed to const once our ABI checker
4728
 *      stops flagging qualifier additions as ABI breaking.
4729
 */
4730
WOLFSSL_ABI
4731
int wolfSSL_pending(WOLFSSL* ssl)
4732
0
{
4733
0
    WOLFSSL_ENTER("wolfSSL_pending");
4734
0
    if (ssl == NULL)
4735
0
        return WOLFSSL_FAILURE;
4736
4737
0
    return (int)ssl->buffers.clearOutputBuffer.length;
4738
0
}
4739
4740
int wolfSSL_has_pending(const WOLFSSL* ssl)
4741
0
{
4742
0
    WOLFSSL_ENTER("wolfSSL_has_pending");
4743
0
    if (ssl == NULL)
4744
0
        return WOLFSSL_FAILURE;
4745
4746
0
    return ssl->buffers.clearOutputBuffer.length > 0;
4747
0
}
4748
4749
#ifndef WOLFSSL_LEANPSK
4750
/* turn on handshake group messages for context */
4751
int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
4752
0
{
4753
0
    if (ctx == NULL)
4754
0
       return BAD_FUNC_ARG;
4755
4756
0
    ctx->groupMessages = 1;
4757
4758
0
    return WOLFSSL_SUCCESS;
4759
0
}
4760
4761
int wolfSSL_CTX_clear_group_messages(WOLFSSL_CTX* ctx)
4762
0
{
4763
0
    if (ctx == NULL)
4764
0
       return BAD_FUNC_ARG;
4765
4766
0
    ctx->groupMessages = 0;
4767
4768
0
    return WOLFSSL_SUCCESS;
4769
0
}
4770
#endif
4771
4772
4773
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
4774
/* connect enough to get peer cert chain */
4775
int wolfSSL_connect_cert(WOLFSSL* ssl)
4776
0
{
4777
0
    int  ret;
4778
4779
0
    if (ssl == NULL)
4780
0
        return WOLFSSL_FAILURE;
4781
4782
0
    ssl->options.certOnly = 1;
4783
0
    ret = wolfSSL_connect(ssl);
4784
0
    ssl->options.certOnly   = 0;
4785
4786
0
    return ret;
4787
0
}
4788
#endif
4789
4790
4791
#ifndef WOLFSSL_LEANPSK
4792
/* turn on handshake group messages for ssl object */
4793
int wolfSSL_set_group_messages(WOLFSSL* ssl)
4794
0
{
4795
0
    if (ssl == NULL)
4796
0
       return BAD_FUNC_ARG;
4797
4798
0
    ssl->options.groupMessages = 1;
4799
4800
0
    return WOLFSSL_SUCCESS;
4801
0
}
4802
4803
int wolfSSL_clear_group_messages(WOLFSSL* ssl)
4804
0
{
4805
0
    if (ssl == NULL)
4806
0
       return BAD_FUNC_ARG;
4807
4808
0
    ssl->options.groupMessages = 0;
4809
4810
0
    return WOLFSSL_SUCCESS;
4811
0
}
4812
4813
/* make minVersion the internal equivalent SSL version */
4814
static int SetMinVersionHelper(byte* minVersion, int version)
4815
0
{
4816
0
    (void)minVersion;
4817
4818
0
    switch (version) {
4819
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4820
        case WOLFSSL_SSLV3:
4821
            *minVersion = SSLv3_MINOR;
4822
            break;
4823
#endif
4824
4825
0
#ifndef NO_TLS
4826
    #ifndef NO_OLD_TLS
4827
        #ifdef WOLFSSL_ALLOW_TLSV10
4828
        case WOLFSSL_TLSV1:
4829
            *minVersion = TLSv1_MINOR;
4830
            break;
4831
        #endif
4832
4833
        case WOLFSSL_TLSV1_1:
4834
            *minVersion = TLSv1_1_MINOR;
4835
            break;
4836
    #endif
4837
0
    #ifndef WOLFSSL_NO_TLS12
4838
0
        case WOLFSSL_TLSV1_2:
4839
0
            *minVersion = TLSv1_2_MINOR;
4840
0
            break;
4841
0
    #endif
4842
0
#endif
4843
0
    #ifdef WOLFSSL_TLS13
4844
0
        case WOLFSSL_TLSV1_3:
4845
0
            *minVersion = TLSv1_3_MINOR;
4846
0
            break;
4847
0
    #endif
4848
4849
#ifdef WOLFSSL_DTLS
4850
        case WOLFSSL_DTLSV1:
4851
            *minVersion = DTLS_MINOR;
4852
            break;
4853
        case WOLFSSL_DTLSV1_2:
4854
            *minVersion = DTLSv1_2_MINOR;
4855
            break;
4856
#ifdef WOLFSSL_DTLS13
4857
        case WOLFSSL_DTLSV1_3:
4858
            *minVersion = DTLSv1_3_MINOR;
4859
            break;
4860
#endif /* WOLFSSL_DTLS13 */
4861
#endif /* WOLFSSL_DTLS */
4862
4863
0
        default:
4864
0
            WOLFSSL_MSG("Bad function argument");
4865
0
            return BAD_FUNC_ARG;
4866
0
    }
4867
4868
0
    return WOLFSSL_SUCCESS;
4869
0
}
4870
4871
4872
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
4873
WOLFSSL_ABI
4874
int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
4875
0
{
4876
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
4877
4878
0
    if (ctx == NULL) {
4879
0
        WOLFSSL_MSG("Bad function argument");
4880
0
        return BAD_FUNC_ARG;
4881
0
    }
4882
4883
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
4884
    if (crypto_policy.enabled) {
4885
        return CRYPTO_POLICY_FORBIDDEN;
4886
    }
4887
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
4888
4889
0
    return SetMinVersionHelper(&ctx->minDowngrade, version);
4890
0
}
4891
4892
4893
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
4894
int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
4895
0
{
4896
0
    WOLFSSL_ENTER("wolfSSL_SetMinVersion");
4897
4898
0
    if (ssl == NULL) {
4899
0
        WOLFSSL_MSG("Bad function argument");
4900
0
        return BAD_FUNC_ARG;
4901
0
    }
4902
4903
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
4904
    if (crypto_policy.enabled) {
4905
        return CRYPTO_POLICY_FORBIDDEN;
4906
    }
4907
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
4908
4909
0
    return SetMinVersionHelper(&ssl->options.minDowngrade, version);
4910
0
}
4911
4912
4913
/* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
4914
int wolfSSL_GetVersion(const WOLFSSL* ssl)
4915
0
{
4916
0
    if (ssl == NULL)
4917
0
        return BAD_FUNC_ARG;
4918
4919
0
    if (ssl->version.major == SSLv3_MAJOR) {
4920
0
        switch (ssl->version.minor) {
4921
0
            case SSLv3_MINOR :
4922
0
                return WOLFSSL_SSLV3;
4923
0
            case TLSv1_MINOR :
4924
0
                return WOLFSSL_TLSV1;
4925
0
            case TLSv1_1_MINOR :
4926
0
                return WOLFSSL_TLSV1_1;
4927
0
            case TLSv1_2_MINOR :
4928
0
                return WOLFSSL_TLSV1_2;
4929
0
            case TLSv1_3_MINOR :
4930
0
                return WOLFSSL_TLSV1_3;
4931
0
            default:
4932
0
                break;
4933
0
        }
4934
0
    }
4935
#ifdef WOLFSSL_DTLS
4936
    if (ssl->version.major == DTLS_MAJOR) {
4937
        switch (ssl->version.minor) {
4938
            case DTLS_MINOR :
4939
                return WOLFSSL_DTLSV1;
4940
            case DTLSv1_2_MINOR :
4941
                return WOLFSSL_DTLSV1_2;
4942
            case DTLSv1_3_MINOR :
4943
                return WOLFSSL_DTLSV1_3;
4944
            default:
4945
                break;
4946
        }
4947
    }
4948
#endif /* WOLFSSL_DTLS */
4949
4950
0
    return VERSION_ERROR;
4951
0
}
4952
4953
int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
4954
0
{
4955
0
    word16 haveRSA = 1;
4956
0
    word16 havePSK = 0;
4957
0
    int    keySz   = 0;
4958
4959
0
    WOLFSSL_ENTER("wolfSSL_SetVersion");
4960
4961
0
    if (ssl == NULL) {
4962
0
        WOLFSSL_MSG("Bad function argument");
4963
0
        return BAD_FUNC_ARG;
4964
0
    }
4965
4966
0
    switch (version) {
4967
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4968
        case WOLFSSL_SSLV3:
4969
            ssl->version = MakeSSLv3();
4970
            break;
4971
#endif
4972
4973
0
#ifndef NO_TLS
4974
    #ifndef NO_OLD_TLS
4975
        #ifdef WOLFSSL_ALLOW_TLSV10
4976
        case WOLFSSL_TLSV1:
4977
            ssl->version = MakeTLSv1();
4978
            break;
4979
        #endif
4980
4981
        case WOLFSSL_TLSV1_1:
4982
            ssl->version = MakeTLSv1_1();
4983
            break;
4984
    #endif
4985
0
    #ifndef WOLFSSL_NO_TLS12
4986
0
        case WOLFSSL_TLSV1_2:
4987
0
            ssl->version = MakeTLSv1_2();
4988
0
            break;
4989
0
    #endif
4990
4991
0
    #ifdef WOLFSSL_TLS13
4992
0
        case WOLFSSL_TLSV1_3:
4993
0
            ssl->version = MakeTLSv1_3();
4994
0
            break;
4995
0
    #endif /* WOLFSSL_TLS13 */
4996
0
#endif
4997
4998
0
        default:
4999
0
            WOLFSSL_MSG("Bad function argument");
5000
0
            return BAD_FUNC_ARG;
5001
0
    }
5002
5003
0
    ssl->options.downgrade = 0;
5004
5005
    #ifdef NO_RSA
5006
        haveRSA = 0;
5007
    #endif
5008
    #ifndef NO_PSK
5009
        havePSK = ssl->options.havePSK;
5010
    #endif
5011
0
    #ifndef NO_CERTS
5012
0
        keySz = ssl->buffers.keySz;
5013
0
    #endif
5014
5015
0
    if (AllocateSuites(ssl) != 0)
5016
0
        return WOLFSSL_FAILURE;
5017
0
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
5018
0
               ssl->options.haveDH, ssl->options.haveECDSAsig,
5019
0
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
5020
0
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
5021
0
    return WOLFSSL_SUCCESS;
5022
0
}
5023
#endif /* !leanpsk */
5024
5025
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
5026
static int wolfSSL_RAND_InitMutex(void);
5027
#endif
5028
5029
/* If we don't have static mutex initializers, but we do have static atomic
5030
 * initializers, activate WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS to leverage
5031
 * the latter.
5032
 *
5033
 * See further explanation below in wolfSSL_Init().
5034
 */
5035
#ifndef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5036
    #if !defined(WOLFSSL_MUTEX_INITIALIZER) && !defined(SINGLE_THREADED) && \
5037
            defined(WOLFSSL_ATOMIC_OPS) && defined(WOLFSSL_ATOMIC_INITIALIZER)
5038
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 1
5039
    #else
5040
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
5041
    #endif
5042
#elif defined(WOLFSSL_MUTEX_INITIALIZER) || defined(SINGLE_THREADED)
5043
    #undef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5044
    #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
5045
#endif
5046
5047
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5048
    #ifndef WOLFSSL_ATOMIC_OPS
5049
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_OPS
5050
    #endif
5051
    #ifndef WOLFSSL_ATOMIC_INITIALIZER
5052
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_INITIALIZER
5053
    #endif
5054
    static wolfSSL_Atomic_Int inits_count_mutex_atomic_initing_flag =
5055
        WOLFSSL_ATOMIC_INITIALIZER(0);
5056
#endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS && !WOLFSSL_MUTEX_INITIALIZER */
5057
5058
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
5059
static void AtExitCleanup(void)
5060
{
5061
    if (initRefCount > 0) {
5062
        initRefCount = 1;
5063
        (void)wolfSSL_Cleanup();
5064
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5065
        if (inits_count_mutex_valid == 1) {
5066
            (void)wc_FreeMutex(&inits_count_mutex);
5067
            inits_count_mutex_valid = 0;
5068
            inits_count_mutex_atomic_initing_flag = 0;
5069
        }
5070
#endif
5071
    }
5072
}
5073
#endif
5074
5075
WOLFSSL_ABI
5076
int wolfSSL_Init(void)
5077
5.23k
{
5078
5.23k
    int ret = WOLFSSL_SUCCESS;
5079
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
5080
    int i;
5081
#endif
5082
5083
5.23k
    WOLFSSL_ENTER("wolfSSL_Init");
5084
5085
5.23k
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
5086
5.23k
    WOLFSSL_MSG(LIBWOLFSSL_CMAKE_OUTPUT);
5087
#else
5088
    WOLFSSL_MSG("No extra wolfSSL cmake messages found");
5089
#endif
5090
5091
#ifndef WOLFSSL_MUTEX_INITIALIZER
5092
    if (inits_count_mutex_valid == 0) {
5093
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5094
5095
        /* Without this mitigation, if two threads enter wolfSSL_Init() at the
5096
         * same time, and both see zero inits_count_mutex_valid, then both will
5097
         * run wc_InitMutex(&inits_count_mutex), leading to process corruption
5098
         * or (best case) a resource leak.
5099
         *
5100
         * When WOLFSSL_ATOMIC_INITIALIZER() is available, we can mitigate this
5101
         * by use an atomic counting int as a mutex.
5102
         */
5103
5104
        if (wolfSSL_Atomic_Int_FetchAdd(&inits_count_mutex_atomic_initing_flag,
5105
                                        1) != 0)
5106
        {
5107
            (void)wolfSSL_Atomic_Int_FetchSub(
5108
                &inits_count_mutex_atomic_initing_flag, 1);
5109
            return DEADLOCK_AVERTED_E;
5110
        }
5111
    #endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS */
5112
        if (wc_InitMutex(&inits_count_mutex) != 0) {
5113
            WOLFSSL_MSG("Bad Init Mutex count");
5114
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
5115
            (void)wolfSSL_Atomic_Int_FetchSub(
5116
                &inits_count_mutex_atomic_initing_flag, 1);
5117
    #endif
5118
            return BAD_MUTEX_E;
5119
        }
5120
        else {
5121
            inits_count_mutex_valid = 1;
5122
        }
5123
    }
5124
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
5125
5126
5.23k
    if (wc_LockMutex(&inits_count_mutex) != 0) {
5127
0
        WOLFSSL_MSG("Bad Lock Mutex count");
5128
0
        return BAD_MUTEX_E;
5129
0
    }
5130
5131
#if FIPS_VERSION_GE(5,1)
5132
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
5133
        ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL);
5134
        if (ret == 0)
5135
            ret = WOLFSSL_SUCCESS;
5136
    }
5137
#endif
5138
5139
5.23k
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
5140
        /* Initialize crypto for use with TLS connection */
5141
5142
5.23k
        if (wolfCrypt_Init() != 0) {
5143
0
            WOLFSSL_MSG("Bad wolfCrypt Init");
5144
0
            ret = WC_INIT_E;
5145
0
        }
5146
5147
#if defined(HAVE_GLOBAL_RNG) && !defined(WOLFSSL_MUTEX_INITIALIZER)
5148
        if (ret == WOLFSSL_SUCCESS) {
5149
            if (wc_InitMutex(&globalRNGMutex) != 0) {
5150
                WOLFSSL_MSG("Bad Init Mutex rng");
5151
                ret = BAD_MUTEX_E;
5152
            }
5153
            else {
5154
                globalRNGMutex_valid = 1;
5155
            }
5156
        }
5157
#endif
5158
5159
    #ifdef WC_RNG_SEED_CB
5160
        wc_SetSeed_Cb(WC_GENERATE_SEED_DEFAULT);
5161
    #endif
5162
5163
#ifdef OPENSSL_EXTRA
5164
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
5165
        if ((ret == WOLFSSL_SUCCESS) && (wolfSSL_RAND_InitMutex() != 0)) {
5166
            ret = BAD_MUTEX_E;
5167
        }
5168
    #endif
5169
        if ((ret == WOLFSSL_SUCCESS) &&
5170
            (wolfSSL_RAND_seed(NULL, 0) != WOLFSSL_SUCCESS)) {
5171
            WOLFSSL_MSG("wolfSSL_RAND_seed failed");
5172
            ret = WC_INIT_E;
5173
        }
5174
#endif
5175
5176
5.23k
#ifndef NO_SESSION_CACHE
5177
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
5178
        for (i = 0; i < SESSION_ROWS; ++i) {
5179
            SessionCache[i].lock_valid = 0;
5180
        }
5181
        for (i = 0; (ret == WOLFSSL_SUCCESS) && (i < SESSION_ROWS); ++i) {
5182
            if (wc_InitRwLock(&SessionCache[i].row_lock) != 0) {
5183
                WOLFSSL_MSG("Bad Init Mutex session");
5184
                ret = BAD_MUTEX_E;
5185
            }
5186
            else {
5187
                SessionCache[i].lock_valid = 1;
5188
            }
5189
        }
5190
    #else
5191
5.23k
        if (ret == WOLFSSL_SUCCESS) {
5192
5.23k
            if (wc_InitRwLock(&session_lock) != 0) {
5193
0
                WOLFSSL_MSG("Bad Init Mutex session");
5194
0
                ret = BAD_MUTEX_E;
5195
0
            }
5196
5.23k
            else {
5197
5.23k
                session_lock_valid = 1;
5198
5.23k
            }
5199
5.23k
        }
5200
5.23k
    #endif
5201
5.23k
    #ifndef NO_CLIENT_CACHE
5202
        #ifndef WOLFSSL_MUTEX_INITIALIZER
5203
        if (ret == WOLFSSL_SUCCESS) {
5204
            if (wc_InitMutex(&clisession_mutex) != 0) {
5205
                WOLFSSL_MSG("Bad Init Mutex session");
5206
                ret = BAD_MUTEX_E;
5207
            }
5208
            else {
5209
                clisession_mutex_valid = 1;
5210
            }
5211
        }
5212
        #endif
5213
5.23k
    #endif
5214
5.23k
#endif
5215
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
5216
        /* OpenSSL registers cleanup using atexit */
5217
        if ((ret == WOLFSSL_SUCCESS) && (atexit(AtExitCleanup) != 0)) {
5218
            WOLFSSL_MSG("Bad atexit registration");
5219
            ret = WC_INIT_E;
5220
        }
5221
#endif
5222
5.23k
    }
5223
5224
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5225
    /* System wide crypto policy disabled by default. */
5226
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
5227
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5228
5229
5.23k
    if (ret == WOLFSSL_SUCCESS) {
5230
5.23k
        initRefCount = initRefCount + 1;
5231
5.23k
    }
5232
0
    else {
5233
0
        initRefCount = 1; /* Force cleanup */
5234
0
    }
5235
5236
5.23k
    wc_UnLockMutex(&inits_count_mutex);
5237
5238
5.23k
    if (ret != WOLFSSL_SUCCESS) {
5239
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
5240
0
    }
5241
5242
5.23k
    return ret;
5243
5.23k
}
5244
5245
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5246
/* Helper function for wolfSSL_crypto_policy_enable and
5247
 * wolfSSL_crypto_policy_enable_buffer.
5248
 *
5249
 * Parses the crypto policy string, verifies values,
5250
 * and sets in global crypto policy struct. Not thread
5251
 * safe. String length has already been verified.
5252
 *
5253
 * Returns WOLFSSL_SUCCESS on success.
5254
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
5255
 * Returns < 0 on misc error.
5256
 * */
5257
static int crypto_policy_parse(void)
5258
{
5259
    const char * hdr = WOLFSSL_SECLEVEL_STR;
5260
    int          sec_level = 0;
5261
    size_t       i = 0;
5262
5263
    /* All policies should begin with "@SECLEVEL=<N>" (N={0..5}) followed
5264
     * by bulk cipher list. */
5265
    if (XMEMCMP(crypto_policy.str, hdr, strlen(hdr)) != 0) {
5266
        WOLFSSL_MSG("error: crypto policy: invalid header");
5267
        return WOLFSSL_BAD_FILE;
5268
    }
5269
5270
    {
5271
        /* Extract the security level. */
5272
        char *       policy_mem = crypto_policy.str;
5273
        policy_mem += strlen(hdr);
5274
        sec_level = (int) (*policy_mem - '0');
5275
    }
5276
5277
    if (sec_level < MIN_WOLFSSL_SEC_LEVEL ||
5278
        sec_level > MAX_WOLFSSL_SEC_LEVEL) {
5279
        WOLFSSL_MSG_EX("error: invalid SECLEVEL: %d", sec_level);
5280
        return WOLFSSL_BAD_FILE;
5281
    }
5282
5283
    /* Remove trailing '\r' or '\n'. */
5284
    for (i = 0; i < MAX_WOLFSSL_CRYPTO_POLICY_SIZE; ++i) {
5285
        if (crypto_policy.str[i] == '\0') {
5286
            break;
5287
        }
5288
5289
        if (crypto_policy.str[i] == '\r' || crypto_policy.str[i] == '\n') {
5290
            crypto_policy.str[i] = '\0';
5291
            break;
5292
        }
5293
    }
5294
5295
    #if defined(DEBUG_WOLFSSL_VERBOSE)
5296
    WOLFSSL_MSG_EX("info: SECLEVEL=%d", sec_level);
5297
    WOLFSSL_MSG_EX("info: using crypto-policy file: %s, %ld", policy_file, sz);
5298
    #endif /* DEBUG_WOLFSSL_VERBOSE */
5299
5300
    crypto_policy.secLevel = sec_level;
5301
    crypto_policy.enabled = 1;
5302
5303
    return WOLFSSL_SUCCESS;
5304
}
5305
5306
#ifndef NO_FILESYSTEM
5307
/* Enables wolfSSL system wide crypto-policy, using the given policy
5308
 * file arg. If NULL is passed, then the default system crypto-policy
5309
 * file that was set at configure time will be used instead.
5310
 *
5311
 * While enabled:
5312
 *   - TLS methods, min key sizes, and cipher lists are all configured
5313
 *     automatically by the policy.
5314
 *   - Attempting to use lesser strength parameters will fail with
5315
 *     error CRYPTO_POLICY_FORBIDDEN.
5316
 *
5317
 * Disable with wolfSSL_crypto_policy_disable.
5318
 *
5319
 * Note: the wolfSSL_crypto_policy_X API are not thread safe, and should
5320
 * only be called at program init time.
5321
 *
5322
 * Returns WOLFSSL_SUCCESS on success.
5323
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
5324
 * Returns < 0 on misc error.
5325
 * */
5326
int wolfSSL_crypto_policy_enable(const char * policy_file)
5327
{
5328
    XFILE   file;
5329
    long    sz = 0;
5330
    size_t  n_read = 0;
5331
5332
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable");
5333
5334
    if (wolfSSL_crypto_policy_is_enabled()) {
5335
        WOLFSSL_MSG_EX("error: crypto policy already enabled: %s",
5336
                       policy_file);
5337
        return CRYPTO_POLICY_FORBIDDEN;
5338
    }
5339
5340
    if (policy_file == NULL) {
5341
        /* Use the configure-time default if NULL passed. */
5342
        policy_file = WC_STRINGIFY(WOLFSSL_CRYPTO_POLICY_FILE);
5343
    }
5344
5345
    if (policy_file == NULL || *policy_file == '\0') {
5346
        WOLFSSL_MSG("error: crypto policy empty file");
5347
        return BAD_FUNC_ARG;
5348
    }
5349
5350
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
5351
5352
    file = XFOPEN(policy_file, "rb");
5353
5354
    if (file == XBADFILE) {
5355
        WOLFSSL_MSG_EX("error: crypto policy file open failed: %s",
5356
                       policy_file);
5357
        return WOLFSSL_BAD_FILE;
5358
    }
5359
5360
    if (XFSEEK(file, 0, XSEEK_END) != 0) {
5361
        WOLFSSL_MSG_EX("error: crypto policy file seek end failed: %s",
5362
                       policy_file);
5363
        XFCLOSE(file);
5364
        return WOLFSSL_BAD_FILE;
5365
    }
5366
5367
    sz = XFTELL(file);
5368
5369
    if (XFSEEK(file, 0, XSEEK_SET) != 0) {
5370
        WOLFSSL_MSG_EX("error: crypto policy file seek failed: %s",
5371
                       policy_file);
5372
        XFCLOSE(file);
5373
        return WOLFSSL_BAD_FILE;
5374
    }
5375
5376
    if (sz <= 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
5377
        WOLFSSL_MSG_EX("error: crypto policy file %s, invalid size: %ld",
5378
                       policy_file, sz);
5379
        XFCLOSE(file);
5380
        return WOLFSSL_BAD_FILE;
5381
    }
5382
5383
    n_read = XFREAD(crypto_policy.str, 1, sz, file);
5384
    XFCLOSE(file);
5385
5386
    if (n_read != (size_t) sz) {
5387
        WOLFSSL_MSG_EX("error: crypto policy file %s: read %zu, "
5388
                       "expected %ld", policy_file, n_read, sz);
5389
        return WOLFSSL_BAD_FILE;
5390
    }
5391
5392
    crypto_policy.str[n_read] = '\0';
5393
5394
    return crypto_policy_parse();
5395
}
5396
#endif /* ! NO_FILESYSTEM */
5397
5398
/* Same behavior as wolfSSL_crypto_policy_enable, but loads
5399
 * via memory buf instead of file.
5400
 *
5401
 * Returns WOLFSSL_SUCCESS on success.
5402
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
5403
 * Returns < 0 on misc error.
5404
 * */
5405
int wolfSSL_crypto_policy_enable_buffer(const char * buf)
5406
{
5407
    size_t sz = 0;
5408
5409
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable_buffer");
5410
5411
    if (wolfSSL_crypto_policy_is_enabled()) {
5412
        WOLFSSL_MSG_EX("error: crypto policy already enabled");
5413
        return CRYPTO_POLICY_FORBIDDEN;
5414
    }
5415
5416
    if (buf == NULL || *buf == '\0') {
5417
        return BAD_FUNC_ARG;
5418
    }
5419
5420
    sz = XSTRLEN(buf);
5421
5422
    if (sz == 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
5423
        return BAD_FUNC_ARG;
5424
    }
5425
5426
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
5427
    XMEMCPY(crypto_policy.str, buf, sz);
5428
5429
    return crypto_policy_parse();
5430
}
5431
5432
/* Returns whether the system wide crypto-policy is enabled.
5433
 *
5434
 * Returns 1 if enabled.
5435
 *         0 if disabled.
5436
 * */
5437
int wolfSSL_crypto_policy_is_enabled(void)
5438
{
5439
    WOLFSSL_ENTER("wolfSSL_crypto_policy_is_enabled");
5440
5441
    return crypto_policy.enabled == 1;
5442
}
5443
5444
/* Disables the system wide crypto-policy.
5445
 * note: SSL and CTX structures already instantiated will
5446
 * keep their security policy parameters. This will only
5447
 * affect new instantiations.
5448
 * */
5449
void wolfSSL_crypto_policy_disable(void)
5450
{
5451
    WOLFSSL_ENTER("wolfSSL_crypto_policy_disable");
5452
    crypto_policy.enabled = 0;
5453
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
5454
    return;
5455
}
5456
5457
/* Get the crypto-policy bulk cipher list string.
5458
 * String is not owned by caller, should not be freed.
5459
 *
5460
 * Returns pointer to bulk cipher list string.
5461
 * Returns NULL if NOT enabled, or on error.
5462
 * */
5463
const char * wolfSSL_crypto_policy_get_ciphers(void)
5464
{
5465
    WOLFSSL_ENTER("wolfSSL_crypto_policy_get_ciphers");
5466
5467
    if (crypto_policy.enabled == 1) {
5468
        /* The crypto policy config will have
5469
         * this form:
5470
         *   "@SECLEVEL=2:kEECDH:kRSA..." */
5471
        return crypto_policy.str;
5472
    }
5473
5474
    return NULL;
5475
}
5476
5477
/* Get the configured crypto-policy security level.
5478
 * A security level of 0 does not impose any additional
5479
 * restrictions.
5480
 *
5481
 * Returns 1 - 5 if enabled.
5482
 * Returns 0 if NOT enabled.
5483
 * */
5484
int wolfSSL_crypto_policy_get_level(void)
5485
{
5486
    if (crypto_policy.enabled == 1) {
5487
        return crypto_policy.secLevel;
5488
    }
5489
5490
    return 0;
5491
}
5492
5493
/* Get security level from ssl structure.
5494
 * @param ssl  a pointer to WOLFSSL structure
5495
 */
5496
int wolfSSL_get_security_level(const WOLFSSL * ssl)
5497
{
5498
    if (ssl == NULL) {
5499
        return BAD_FUNC_ARG;
5500
    }
5501
5502
    return ssl->secLevel;
5503
}
5504
5505
#ifndef NO_WOLFSSL_STUB
5506
/*
5507
 * Set security level (wolfSSL doesn't support setting the security level).
5508
 *
5509
 * The security level can only be set through a system wide crypto-policy
5510
 * with wolfSSL_crypto_policy_enable().
5511
 *
5512
 * @param ssl  a pointer to WOLFSSL structure
5513
 * @param level security level
5514
 */
5515
void wolfSSL_set_security_level(WOLFSSL * ssl, int level)
5516
{
5517
    WOLFSSL_ENTER("wolfSSL_set_security_level");
5518
    (void)ssl;
5519
    (void)level;
5520
}
5521
#endif /* !NO_WOLFSSL_STUB */
5522
5523
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5524
5525
5526
#define WOLFSSL_SSL_LOAD_INCLUDED
5527
#include <src/ssl_load.c>
5528
5529
#define WOLFSSL_SSL_API_CRL_OCSP_INCLUDED
5530
#include "src/ssl_api_crl_ocsp.c"
5531
5532
5533
void wolfSSL_load_error_strings(void)
5534
0
{
5535
    /* compatibility only */
5536
0
}
5537
5538
5539
int wolfSSL_library_init(void)
5540
0
{
5541
0
    WOLFSSL_ENTER("wolfSSL_library_init");
5542
0
    if (wolfSSL_Init() == WOLFSSL_SUCCESS)
5543
0
        return WOLFSSL_SUCCESS;
5544
0
    else
5545
0
        return WOLFSSL_FATAL_ERROR;
5546
0
}
5547
5548
5549
#ifdef HAVE_SECRET_CALLBACK
5550
5551
int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx)
5552
{
5553
    WOLFSSL_ENTER("wolfSSL_set_session_secret_cb");
5554
    if (ssl == NULL)
5555
        return WOLFSSL_FAILURE;
5556
5557
    ssl->sessionSecretCb = cb;
5558
    ssl->sessionSecretCtx = ctx;
5559
    if (cb != NULL) {
5560
        /* If using a pre-set key, assume session resumption. */
5561
        ssl->session->sessionIDSz = 0;
5562
        ssl->options.resuming = 1;
5563
    }
5564
5565
    return WOLFSSL_SUCCESS;
5566
}
5567
5568
int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, TicketParseCb cb,
5569
        void *ctx)
5570
{
5571
    WOLFSSL_ENTER("wolfSSL_set_session_ticket_ext_cb");
5572
    if (ssl == NULL)
5573
        return WOLFSSL_FAILURE;
5574
5575
    ssl->ticketParseCb = cb;
5576
    ssl->ticketParseCtx = ctx;
5577
5578
    return WOLFSSL_SUCCESS;
5579
}
5580
5581
int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx)
5582
{
5583
    WOLFSSL_ENTER("wolfSSL_set_secret_cb");
5584
    if (ssl == NULL)
5585
        return WOLFSSL_FATAL_ERROR;
5586
5587
    ssl->tlsSecretCb = cb;
5588
    ssl->tlsSecretCtx = ctx;
5589
5590
    return WOLFSSL_SUCCESS;
5591
}
5592
5593
#ifdef SHOW_SECRETS
5594
int tlsShowSecrets(WOLFSSL* ssl, void* secret, int secretSz,
5595
        void* ctx)
5596
{
5597
    /* Wireshark Pre-Master-Secret Format:
5598
     *  CLIENT_RANDOM <clientrandom> <mastersecret>
5599
     */
5600
    const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
5601
    int i, pmsPos = 0;
5602
    char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
5603
    byte clientRandom[RAN_LEN];
5604
    int clientRandomSz;
5605
5606
    (void)ctx;
5607
5608
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
5609
        sizeof(clientRandom));
5610
5611
    if (clientRandomSz <= 0) {
5612
        printf("Error getting server random %d\n", clientRandomSz);
5613
        return BAD_FUNC_ARG;
5614
    }
5615
5616
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
5617
        CLIENT_RANDOM_LABEL);
5618
    pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
5619
    for (i = 0; i < clientRandomSz; i++) {
5620
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
5621
            clientRandom[i]);
5622
        pmsPos += 2;
5623
    }
5624
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
5625
    pmsPos += 1;
5626
    for (i = 0; i < secretSz; i++) {
5627
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
5628
            ((byte*)secret)[i]);
5629
        pmsPos += 2;
5630
    }
5631
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
5632
    pmsPos += 1;
5633
5634
    /* print master secret */
5635
    puts(pmsBuf);
5636
5637
    #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
5638
    {
5639
        FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
5640
        if (f != XBADFILE) {
5641
            XFWRITE(pmsBuf, 1, pmsPos, f);
5642
            XFCLOSE(f);
5643
        }
5644
    }
5645
    #endif
5646
    return 0;
5647
}
5648
#endif /* SHOW_SECRETS */
5649
5650
#endif
5651
5652
5653
#ifdef OPENSSL_EXTRA
5654
5655
/*
5656
 * check if the list has TLS13 and pre-TLS13 suites
5657
 * @param list cipher suite list that user want to set
5658
 *         (caller required to check for NULL)
5659
 * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
5660
 */
5661
static int CheckcipherList(const char* list)
5662
{
5663
    int ret;
5664
    int findTLSv13Suites = 0;
5665
    int findbeforeSuites = 0;
5666
    byte cipherSuite0;
5667
    byte cipherSuite1;
5668
    int flags;
5669
    char* next = (char*)list;
5670
5671
    do {
5672
        char*  current = next;
5673
        char   name[MAX_SUITE_NAME + 1];
5674
        word32 length = MAX_SUITE_NAME;
5675
        word32 current_length;
5676
        byte major = INVALID_BYTE;
5677
        byte minor = INVALID_BYTE;
5678
5679
        next   = XSTRSTR(next, ":");
5680
5681
        if (next) {
5682
            current_length = (word32)(next - current);
5683
            ++next; /* increment to skip ':' */
5684
        }
5685
        else {
5686
            current_length = (word32)XSTRLEN(current);
5687
        }
5688
5689
        if (current_length == 0) {
5690
            break;
5691
        }
5692
5693
        if (current_length < length) {
5694
            length = current_length;
5695
        }
5696
        XMEMCPY(name, current, length);
5697
        name[length] = 0;
5698
5699
        if (XSTRCMP(name, "ALL") == 0 ||
5700
            XSTRCMP(name, "DEFAULT") == 0 ||
5701
            XSTRCMP(name, "HIGH") == 0)
5702
        {
5703
            findTLSv13Suites = 1;
5704
            findbeforeSuites = 1;
5705
            break;
5706
        }
5707
5708
        ret = GetCipherSuiteFromName(name, &cipherSuite0,
5709
                &cipherSuite1, &major, &minor, &flags);
5710
        if (ret == 0) {
5711
            if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) {
5712
                /* TLSv13 suite */
5713
                findTLSv13Suites = 1;
5714
            }
5715
            else {
5716
                findbeforeSuites = 1;
5717
            }
5718
        }
5719
5720
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
5721
        /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */
5722
        if (ret != 0) {
5723
            char* subStr = name;
5724
            char* subStrNext;
5725
5726
            do {
5727
                subStrNext = XSTRSTR(subStr, "+");
5728
5729
                if ((XSTRCMP(subStr, "ECDHE") == 0) ||
5730
                    (XSTRCMP(subStr, "RSA") == 0)) {
5731
                    return 0;
5732
                }
5733
5734
                if (subStrNext && (XSTRLEN(subStrNext) > 0)) {
5735
                    subStr = subStrNext + 1; /* +1 to skip past '+' */
5736
                }
5737
            } while (subStrNext != NULL);
5738
        }
5739
    #endif
5740
5741
        if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
5742
            /* list has mixed suites */
5743
            return 0;
5744
        }
5745
    } while (next);
5746
5747
    if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
5748
        ret = 1;/* only before TLSv13 suites */
5749
    }
5750
    else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
5751
        ret = 2;/* only TLSv13 suties */
5752
    }
5753
    else {
5754
        ret = 0;/* handle as mixed */
5755
    }
5756
    return ret;
5757
}
5758
5759
/* parse some bulk lists like !eNULL / !aNULL
5760
 *
5761
 * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
5762
 */
5763
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
5764
        Suites* suites, const char* list)
5765
{
5766
    int     ret = 0;
5767
    int     listattribute = 0;
5768
    int     tls13Only = 0;
5769
    WC_DECLARE_VAR(suitesCpy, byte, WOLFSSL_MAX_SUITE_SZ, 0);
5770
    word16  suitesCpySz = 0;
5771
    word16  i = 0;
5772
    word16  j = 0;
5773
5774
    if (suites == NULL || list == NULL) {
5775
        WOLFSSL_MSG("NULL argument");
5776
        return WOLFSSL_FAILURE;
5777
    }
5778
5779
    listattribute = CheckcipherList(list);
5780
5781
    if (listattribute == 0) {
5782
       /* list has mixed(pre-TLSv13 and TLSv13) suites
5783
        * update cipher suites the same as before
5784
        */
5785
        return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS :
5786
        WOLFSSL_FAILURE;
5787
    }
5788
    else if (listattribute == 1) {
5789
       /* list has only pre-TLSv13 suites.
5790
        * Only update before TLSv13 suites.
5791
        */
5792
        tls13Only = 0;
5793
    }
5794
    else if (listattribute == 2) {
5795
       /* list has only TLSv13 suites. Only update TLv13 suites
5796
        * simulate set_ciphersuites() compatibility layer API
5797
        */
5798
        tls13Only = 1;
5799
        if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) ||
5800
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) {
5801
            /* Silently ignore TLS 1.3 ciphers if we don't support it. */
5802
            return WOLFSSL_SUCCESS;
5803
        }
5804
    }
5805
5806
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
5807
#ifdef WOLFSSL_SMALL_STACK
5808
    if (suites->suiteSz > 0) {
5809
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
5810
                DYNAMIC_TYPE_TMP_BUFFER);
5811
        if (suitesCpy == NULL) {
5812
            return WOLFSSL_FAILURE;
5813
        }
5814
5815
        XMEMSET(suitesCpy, 0, suites->suiteSz);
5816
    }
5817
#else
5818
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
5819
#endif
5820
5821
    if (suites->suiteSz > 0)
5822
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
5823
    suitesCpySz = suites->suiteSz;
5824
5825
    ret = SetCipherList_ex(ctx, ssl, suites, list);
5826
    if (ret != 1) {
5827
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5828
        return WOLFSSL_FAILURE;
5829
    }
5830
5831
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
5832
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
5833
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
5834
     * Since we direct both API here we attempt to provide API compatibility. If
5835
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
5836
     * suites and keep the suites from the other group.
5837
     * If downgrade is disabled, skip preserving the other group's suites. */
5838
    if ((ssl != NULL && !ssl->options.downgrade) ||
5839
        (ctx != NULL && !ctx->method->downgrade)) {
5840
        /* Downgrade disabled - don't preserve other group's suites */
5841
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5842
        return ret;
5843
    }
5844
5845
    for (i = 0; i < suitesCpySz &&
5846
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
5847
        /* Check for duplicates */
5848
        int duplicate = 0;
5849
        for (j = 0; j < suites->suiteSz; j += 2) {
5850
            if (suitesCpy[i] == suites->suites[j] &&
5851
                    suitesCpy[i+1] == suites->suites[j+1]) {
5852
                duplicate = 1;
5853
                break;
5854
            }
5855
        }
5856
        if (!duplicate) {
5857
            if (tls13Only) {
5858
                /* Updating TLS 1.3 ciphers */
5859
                if (suitesCpy[i] != TLS13_BYTE) {
5860
                    /* Only copy over <= TLS 1.2 ciphers */
5861
                    /* TLS 1.3 ciphers take precedence */
5862
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
5863
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
5864
                }
5865
            }
5866
            else {
5867
                /* Updating <= TLS 1.2 ciphers */
5868
                if (suitesCpy[i] == TLS13_BYTE) {
5869
                    /* Only copy over TLS 1.3 ciphers */
5870
                    /* TLS 1.3 ciphers take precedence */
5871
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
5872
                             suites->suiteSz);
5873
                    suites->suites[0] = suitesCpy[i];
5874
                    suites->suites[1] = suitesCpy[i+1];
5875
                    suites->suiteSz += 2;
5876
                }
5877
            }
5878
        }
5879
    }
5880
5881
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5882
    return ret;
5883
}
5884
5885
#endif
5886
5887
5888
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
5889
0
{
5890
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
5891
5892
0
    if (ctx == NULL)
5893
0
        return WOLFSSL_FAILURE;
5894
5895
0
    if (AllocateCtxSuites(ctx) != 0)
5896
0
        return WOLFSSL_FAILURE;
5897
5898
#ifdef OPENSSL_EXTRA
5899
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
5900
#else
5901
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
5902
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
5903
0
#endif
5904
0
}
5905
5906
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
5907
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
5908
                                      const int listSz)
5909
{
5910
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
5911
5912
    if (ctx == NULL)
5913
        return WOLFSSL_FAILURE;
5914
5915
    if (AllocateCtxSuites(ctx) != 0)
5916
        return WOLFSSL_FAILURE;
5917
5918
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
5919
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
5920
}
5921
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
5922
5923
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
5924
0
{
5925
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
5926
5927
0
    if (ssl == NULL || ssl->ctx == NULL) {
5928
0
        return WOLFSSL_FAILURE;
5929
0
    }
5930
5931
0
    if (AllocateSuites(ssl) != 0)
5932
0
        return WOLFSSL_FAILURE;
5933
5934
#ifdef OPENSSL_EXTRA
5935
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
5936
#else
5937
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
5938
0
        WOLFSSL_SUCCESS :
5939
0
        WOLFSSL_FAILURE;
5940
0
#endif
5941
0
}
5942
5943
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
5944
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
5945
                                  const int listSz)
5946
{
5947
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
5948
5949
    if (ssl == NULL || ssl->ctx == NULL) {
5950
        return WOLFSSL_FAILURE;
5951
    }
5952
5953
    if (AllocateSuites(ssl) != 0)
5954
        return WOLFSSL_FAILURE;
5955
5956
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
5957
           ? WOLFSSL_SUCCESS
5958
           : WOLFSSL_FAILURE;
5959
}
5960
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
5961
5962
5963
#ifdef HAVE_KEYING_MATERIAL
5964
5965
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
5966
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
5967
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
5968
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
5969
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
5970
5971
static const struct ForbiddenLabels {
5972
    const char* label;
5973
    size_t labelLen;
5974
} forbiddenLabels[] = {
5975
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
5976
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
5977
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
5978
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
5979
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
5980
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
5981
    {NULL, 0},
5982
};
5983
5984
/**
5985
 * Implement RFC 5705
5986
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
5987
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
5988
 */
5989
int wolfSSL_export_keying_material(WOLFSSL *ssl,
5990
        unsigned char *out, size_t outLen,
5991
        const char *label, size_t labelLen,
5992
        const unsigned char *context, size_t contextLen,
5993
        int use_context)
5994
{
5995
    byte*  seed = NULL;
5996
    word32 seedLen;
5997
    const struct ForbiddenLabels* fl;
5998
5999
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
6000
6001
    if (ssl == NULL || out == NULL || label == NULL ||
6002
            (use_context && contextLen && context == NULL)) {
6003
        WOLFSSL_MSG("Bad argument");
6004
        return WOLFSSL_FAILURE;
6005
    }
6006
6007
    /* Sanity check contextLen to prevent integer overflow when cast to word32
6008
     * and to ensure it fits in the 2-byte length encoding (max 65535). */
6009
    if (use_context && contextLen > WOLFSSL_MAX_16BIT) {
6010
        WOLFSSL_MSG("contextLen too large");
6011
        return WOLFSSL_FAILURE;
6012
    }
6013
6014
    /* clientRandom + serverRandom
6015
     * OR
6016
     * clientRandom + serverRandom + ctx len encoding + ctx */
6017
    seedLen = !use_context ? (word32)SEED_LEN :
6018
                             (word32)SEED_LEN + 2 + (word32)contextLen;
6019
6020
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
6021
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
6022
                    "data. Call wolfSSL_KeepArrays before attempting to "
6023
                    "export keyid material.");
6024
        return WOLFSSL_FAILURE;
6025
    }
6026
6027
    /* check forbidden labels */
6028
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
6029
        if (labelLen >= fl->labelLen &&
6030
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
6031
            WOLFSSL_MSG("Forbidden label");
6032
            return WOLFSSL_FAILURE;
6033
        }
6034
    }
6035
6036
#ifdef WOLFSSL_TLS13
6037
    if (IsAtLeastTLSv1_3(ssl->version)) {
6038
        /* Path for TLS 1.3 */
6039
        if (!use_context) {
6040
            contextLen = 0;
6041
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
6042
        }
6043
6044
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
6045
                context, contextLen) != 0) {
6046
            WOLFSSL_MSG("Tls13_Exporter error");
6047
            return WOLFSSL_FAILURE;
6048
        }
6049
        return WOLFSSL_SUCCESS;
6050
    }
6051
#endif
6052
6053
    /* Path for <=TLS 1.2 */
6054
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6055
    if (seed == NULL) {
6056
        WOLFSSL_MSG("malloc error");
6057
        return WOLFSSL_FAILURE;
6058
    }
6059
6060
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
6061
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
6062
6063
    if (use_context) {
6064
        /* Encode len in big endian */
6065
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
6066
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
6067
        if (contextLen) {
6068
            /* 0 length context is allowed */
6069
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
6070
        }
6071
    }
6072
6073
    PRIVATE_KEY_UNLOCK();
6074
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
6075
            (byte*)label, (word32)labelLen, seed, seedLen,
6076
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
6077
            ssl->devId) != 0) {
6078
        WOLFSSL_MSG("wc_PRF_TLS error");
6079
        PRIVATE_KEY_LOCK();
6080
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6081
        return WOLFSSL_FAILURE;
6082
    }
6083
    PRIVATE_KEY_LOCK();
6084
6085
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
6086
    return WOLFSSL_SUCCESS;
6087
}
6088
#endif /* HAVE_KEYING_MATERIAL */
6089
6090
int wolfSSL_dtls_get_using_nonblock(WOLFSSL* ssl)
6091
0
{
6092
0
    int useNb = 0;
6093
6094
0
    if (ssl == NULL)
6095
0
        return WOLFSSL_FAILURE;
6096
6097
0
    WOLFSSL_ENTER("wolfSSL_dtls_get_using_nonblock");
6098
0
    if (ssl->options.dtls) {
6099
#ifdef WOLFSSL_DTLS
6100
        useNb = ssl->options.dtlsUseNonblock;
6101
#endif
6102
0
    }
6103
0
    else {
6104
0
        WOLFSSL_MSG("wolfSSL_dtls_get_using_nonblock() is "
6105
0
                    "DEPRECATED for non-DTLS use.");
6106
0
    }
6107
0
    return useNb;
6108
0
}
6109
6110
6111
#ifndef WOLFSSL_LEANPSK
6112
6113
void wolfSSL_dtls_set_using_nonblock(WOLFSSL* ssl, int nonblock)
6114
0
{
6115
0
    (void)nonblock;
6116
6117
0
    WOLFSSL_ENTER("wolfSSL_dtls_set_using_nonblock");
6118
6119
0
    if (ssl == NULL)
6120
0
        return;
6121
6122
0
    if (ssl->options.dtls) {
6123
#ifdef WOLFSSL_DTLS
6124
        ssl->options.dtlsUseNonblock = (nonblock != 0);
6125
#endif
6126
0
    }
6127
0
    else {
6128
0
        WOLFSSL_MSG("wolfSSL_dtls_set_using_nonblock() is "
6129
0
                    "DEPRECATED for non-DTLS use.");
6130
0
    }
6131
0
}
6132
6133
6134
#ifdef WOLFSSL_DTLS
6135
6136
int wolfSSL_dtls_get_current_timeout(WOLFSSL* ssl)
6137
{
6138
    int timeout = 0;
6139
    if (ssl)
6140
        timeout = ssl->dtls_timeout;
6141
6142
    WOLFSSL_LEAVE("wolfSSL_dtls_get_current_timeout", timeout);
6143
    return timeout;
6144
}
6145
6146
#ifdef WOLFSSL_DTLS13
6147
6148
/*
6149
 * This API returns 1 when the user should set a short timeout for receiving
6150
 * data. It is recommended that it is at most 1/4 the value returned by
6151
 * wolfSSL_dtls_get_current_timeout().
6152
 */
6153
int wolfSSL_dtls13_use_quick_timeout(WOLFSSL* ssl)
6154
{
6155
    return ssl != NULL && ssl->dtls13FastTimeout;
6156
}
6157
6158
/*
6159
 * When this is set, a DTLS 1.3 connection will send acks immediately when a
6160
 * disruption is detected to shortcut timeouts. This results in potentially
6161
 * more traffic but may make the handshake quicker.
6162
 */
6163
void wolfSSL_dtls13_set_send_more_acks(WOLFSSL* ssl, int value)
6164
{
6165
    if (ssl != NULL)
6166
        ssl->options.dtls13SendMoreAcks = !!value;
6167
}
6168
#endif /* WOLFSSL_DTLS13 */
6169
6170
int wolfSSL_DTLSv1_get_timeout(WOLFSSL* ssl, WOLFSSL_TIMEVAL* timeleft)
6171
{
6172
    if (ssl && timeleft) {
6173
        XMEMSET(timeleft, 0, sizeof(WOLFSSL_TIMEVAL));
6174
        timeleft->tv_sec = ssl->dtls_timeout;
6175
    }
6176
    return 0;
6177
}
6178
6179
#ifndef NO_WOLFSSL_STUB
6180
int wolfSSL_DTLSv1_handle_timeout(WOLFSSL* ssl)
6181
{
6182
    WOLFSSL_STUB("SSL_DTLSv1_handle_timeout");
6183
    (void)ssl;
6184
    return 0;
6185
}
6186
#endif
6187
6188
#ifndef NO_WOLFSSL_STUB
6189
void wolfSSL_DTLSv1_set_initial_timeout_duration(WOLFSSL* ssl,
6190
    word32 duration_ms)
6191
{
6192
    WOLFSSL_STUB("SSL_DTLSv1_set_initial_timeout_duration");
6193
    (void)ssl;
6194
    (void)duration_ms;
6195
}
6196
#endif
6197
6198
/* user may need to alter init dtls recv timeout, WOLFSSL_SUCCESS on ok */
6199
int wolfSSL_dtls_set_timeout_init(WOLFSSL* ssl, int timeout)
6200
{
6201
    if (ssl == NULL || timeout < 0)
6202
        return BAD_FUNC_ARG;
6203
6204
    if (timeout > ssl->dtls_timeout_max) {
6205
        WOLFSSL_MSG("Can't set dtls timeout init greater than dtls timeout "
6206
                    "max");
6207
        return BAD_FUNC_ARG;
6208
    }
6209
6210
    ssl->dtls_timeout_init = timeout;
6211
    ssl->dtls_timeout = timeout;
6212
6213
    return WOLFSSL_SUCCESS;
6214
}
6215
6216
6217
/* user may need to alter max dtls recv timeout, WOLFSSL_SUCCESS on ok */
6218
int wolfSSL_dtls_set_timeout_max(WOLFSSL* ssl, int timeout)
6219
{
6220
    if (ssl == NULL || timeout < 0)
6221
        return BAD_FUNC_ARG;
6222
6223
    if (timeout < ssl->dtls_timeout_init) {
6224
        WOLFSSL_MSG("Can't set dtls timeout max less than dtls timeout init");
6225
        return BAD_FUNC_ARG;
6226
    }
6227
6228
    ssl->dtls_timeout_max = timeout;
6229
6230
    return WOLFSSL_SUCCESS;
6231
}
6232
6233
6234
int wolfSSL_dtls_got_timeout(WOLFSSL* ssl)
6235
{
6236
    int result = WOLFSSL_SUCCESS;
6237
    WOLFSSL_ENTER("wolfSSL_dtls_got_timeout");
6238
6239
    if (ssl == NULL || !ssl->options.dtls)
6240
        return WOLFSSL_FATAL_ERROR;
6241
6242
#ifdef WOLFSSL_DTLS13
6243
    if (IsAtLeastTLSv1_3(ssl->version)) {
6244
        result = Dtls13RtxTimeout(ssl);
6245
        if (result < 0) {
6246
            if (result == WC_NO_ERR_TRACE(WANT_WRITE))
6247
                ssl->dtls13SendingAckOrRtx = 1;
6248
            ssl->error = result;
6249
            WOLFSSL_ERROR(result);
6250
            return WOLFSSL_FATAL_ERROR;
6251
        }
6252
6253
        return WOLFSSL_SUCCESS;
6254
    }
6255
#endif /* WOLFSSL_DTLS13 */
6256
6257
    /* Do we have any 1.2 messages stored? */
6258
    if (ssl->dtls_tx_msg_list != NULL || ssl->dtls_tx_msg != NULL) {
6259
        if (DtlsMsgPoolTimeout(ssl) < 0){
6260
            ssl->error = SOCKET_ERROR_E;
6261
            WOLFSSL_ERROR(ssl->error);
6262
            result = WOLFSSL_FATAL_ERROR;
6263
        }
6264
        else if ((result = DtlsMsgPoolSend(ssl, 0)) < 0)  {
6265
            ssl->error = result;
6266
            WOLFSSL_ERROR(result);
6267
            result = WOLFSSL_FATAL_ERROR;
6268
        }
6269
        else {
6270
            /* Reset return value to success */
6271
            result = WOLFSSL_SUCCESS;
6272
        }
6273
    }
6274
6275
    WOLFSSL_LEAVE("wolfSSL_dtls_got_timeout", result);
6276
    return result;
6277
}
6278
6279
6280
/* retransmit all the saves messages, WOLFSSL_SUCCESS on ok */
6281
int wolfSSL_dtls_retransmit(WOLFSSL* ssl)
6282
{
6283
    WOLFSSL_ENTER("wolfSSL_dtls_retransmit");
6284
6285
    if (ssl == NULL)
6286
        return WOLFSSL_FATAL_ERROR;
6287
6288
    if (!ssl->options.handShakeDone) {
6289
        int result;
6290
#ifdef WOLFSSL_DTLS13
6291
        if (IsAtLeastTLSv1_3(ssl->version))
6292
            result = Dtls13DoScheduledWork(ssl);
6293
        else
6294
#endif
6295
            result = DtlsMsgPoolSend(ssl, 0);
6296
        if (result < 0) {
6297
            ssl->error = result;
6298
            WOLFSSL_ERROR(result);
6299
            return WOLFSSL_FATAL_ERROR;
6300
        }
6301
    }
6302
6303
    return WOLFSSL_SUCCESS;
6304
}
6305
6306
#endif /* DTLS */
6307
#endif /* LEANPSK */
6308
6309
6310
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
6311
6312
/* Not an SSL function, return 0 for success, error code otherwise */
6313
/* Prereq: ssl's RNG needs to be initialized. */
6314
int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl,
6315
                                 const byte* secret, word32 secretSz)
6316
{
6317
    int ret = 0;
6318
6319
    WOLFSSL_ENTER("wolfSSL_DTLS_SetCookieSecret");
6320
6321
    if (ssl == NULL) {
6322
        WOLFSSL_MSG("need a SSL object");
6323
        return BAD_FUNC_ARG;
6324
    }
6325
6326
    if (secret != NULL && secretSz == 0) {
6327
        WOLFSSL_MSG("can't have a new secret without a size");
6328
        return BAD_FUNC_ARG;
6329
    }
6330
6331
    /* If secretSz is 0, use the default size. */
6332
    if (secretSz == 0)
6333
        secretSz = COOKIE_SECRET_SZ;
6334
6335
    if (secretSz != ssl->buffers.dtlsCookieSecret.length) {
6336
        byte* newSecret;
6337
6338
        if (ssl->buffers.dtlsCookieSecret.buffer != NULL) {
6339
            ForceZero(ssl->buffers.dtlsCookieSecret.buffer,
6340
                      ssl->buffers.dtlsCookieSecret.length);
6341
            XFREE(ssl->buffers.dtlsCookieSecret.buffer,
6342
                  ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
6343
        }
6344
6345
        newSecret = (byte*)XMALLOC(secretSz, ssl->heap,DYNAMIC_TYPE_COOKIE_PWD);
6346
        if (newSecret == NULL) {
6347
            ssl->buffers.dtlsCookieSecret.buffer = NULL;
6348
            ssl->buffers.dtlsCookieSecret.length = 0;
6349
            WOLFSSL_MSG("couldn't allocate new cookie secret");
6350
            return MEMORY_ERROR;
6351
        }
6352
        ssl->buffers.dtlsCookieSecret.buffer = newSecret;
6353
        ssl->buffers.dtlsCookieSecret.length = secretSz;
6354
    #ifdef WOLFSSL_CHECK_MEM_ZERO
6355
        wc_MemZero_Add("wolfSSL_DTLS_SetCookieSecret secret",
6356
            ssl->buffers.dtlsCookieSecret.buffer,
6357
            ssl->buffers.dtlsCookieSecret.length);
6358
    #endif
6359
    }
6360
6361
    /* If the supplied secret is NULL, randomly generate a new secret. */
6362
    if (secret == NULL) {
6363
        ret = wc_RNG_GenerateBlock(ssl->rng,
6364
                             ssl->buffers.dtlsCookieSecret.buffer, secretSz);
6365
    }
6366
    else
6367
        XMEMCPY(ssl->buffers.dtlsCookieSecret.buffer, secret, secretSz);
6368
6369
    WOLFSSL_LEAVE("wolfSSL_DTLS_SetCookieSecret", 0);
6370
    return ret;
6371
}
6372
6373
#endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
6374
6375
6376
/* EITHER SIDE METHODS */
6377
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
6378
    WOLFSSL_METHOD* wolfSSLv23_method(void)
6379
    {
6380
        return wolfSSLv23_method_ex(NULL);
6381
    }
6382
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
6383
    {
6384
        WOLFSSL_METHOD* m = NULL;
6385
        WOLFSSL_ENTER("wolfSSLv23_method");
6386
    #if !defined(NO_WOLFSSL_CLIENT)
6387
        m = wolfSSLv23_client_method_ex(heap);
6388
    #elif !defined(NO_WOLFSSL_SERVER)
6389
        m = wolfSSLv23_server_method_ex(heap);
6390
    #else
6391
        (void)heap;
6392
    #endif
6393
        if (m != NULL) {
6394
            m->side = WOLFSSL_NEITHER_END;
6395
        }
6396
6397
        return m;
6398
    }
6399
6400
    #ifndef NO_OLD_TLS
6401
    #ifdef WOLFSSL_ALLOW_SSLV3
6402
    WOLFSSL_METHOD* wolfSSLv3_method(void)
6403
    {
6404
        return wolfSSLv3_method_ex(NULL);
6405
    }
6406
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
6407
    {
6408
        WOLFSSL_METHOD* m = NULL;
6409
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
6410
    #if !defined(NO_WOLFSSL_CLIENT)
6411
        m = wolfSSLv3_client_method_ex(heap);
6412
    #elif !defined(NO_WOLFSSL_SERVER)
6413
        m = wolfSSLv3_server_method_ex(heap);
6414
    #endif
6415
        if (m != NULL) {
6416
            m->side = WOLFSSL_NEITHER_END;
6417
        }
6418
6419
        return m;
6420
    }
6421
    #endif
6422
    #endif
6423
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
6424
6425
/* client only parts */
6426
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
6427
6428
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
6429
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
6430
    {
6431
        WOLFSSL_STUB("wolfSSLv2_client_method");
6432
        return NULL;
6433
    }
6434
    #endif
6435
6436
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
6437
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
6438
    {
6439
        return wolfSSLv3_client_method_ex(NULL);
6440
    }
6441
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
6442
    {
6443
        WOLFSSL_METHOD* method =
6444
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
6445
                                                     heap, DYNAMIC_TYPE_METHOD);
6446
        (void)heap;
6447
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
6448
        if (method)
6449
            InitSSL_Method(method, MakeSSLv3());
6450
        return method;
6451
    }
6452
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
6453
6454
6455
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
6456
0
    {
6457
0
        return wolfSSLv23_client_method_ex(NULL);
6458
0
    }
6459
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
6460
0
    {
6461
0
        WOLFSSL_METHOD* method =
6462
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
6463
0
                                                     heap, DYNAMIC_TYPE_METHOD);
6464
0
        (void)heap;
6465
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
6466
0
        if (method) {
6467
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
6468
0
        defined(WOLFSSL_SHA512)
6469
0
        #if defined(WOLFSSL_TLS13)
6470
0
            InitSSL_Method(method, MakeTLSv1_3());
6471
        #elif !defined(WOLFSSL_NO_TLS12)
6472
            InitSSL_Method(method, MakeTLSv1_2());
6473
        #elif !defined(NO_OLD_TLS)
6474
            InitSSL_Method(method, MakeTLSv1_1());
6475
        #endif
6476
    #else
6477
        #ifndef NO_OLD_TLS
6478
            InitSSL_Method(method, MakeTLSv1_1());
6479
        #endif
6480
    #endif
6481
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
6482
0
            method->downgrade = 1;
6483
0
    #endif
6484
0
        }
6485
0
        return method;
6486
0
    }
6487
6488
    /* please see note at top of README if you get an error from connect */
6489
    WOLFSSL_ABI
6490
    int wolfSSL_connect(WOLFSSL* ssl)
6491
    {
6492
    #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
6493
          defined(WOLFSSL_TLS13))
6494
        int neededState;
6495
        byte advanceState;
6496
    #endif
6497
        int ret = 0;
6498
6499
        (void)ret;
6500
6501
        #ifdef HAVE_ERRNO_H
6502
            errno = 0;
6503
        #endif
6504
6505
        if (ssl == NULL)
6506
            return BAD_FUNC_ARG;
6507
6508
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
6509
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
6510
            ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
6511
            if (ssl->error != WOLFSSL_SUCCESS) {
6512
                WOLFSSL_ERROR(ssl->error);
6513
                return WOLFSSL_FATAL_ERROR;
6514
            }
6515
            ssl->error = 0; /* expected to be zero here */
6516
        }
6517
6518
    #ifdef OPENSSL_EXTRA
6519
        if (ssl->CBIS != NULL) {
6520
            ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS);
6521
            ssl->cbmode = WOLFSSL_CB_WRITE;
6522
        }
6523
    #endif
6524
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
6525
6526
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
6527
        defined(WOLFSSL_TLS13)
6528
        return wolfSSL_connect_TLSv13(ssl);
6529
    #else
6530
        #ifdef WOLFSSL_TLS13
6531
        if (ssl->options.tls1_3) {
6532
            WOLFSSL_MSG("TLS 1.3");
6533
            return wolfSSL_connect_TLSv13(ssl);
6534
        }
6535
        #endif
6536
6537
        WOLFSSL_MSG("TLS 1.2 or lower");
6538
        WOLFSSL_ENTER("wolfSSL_connect");
6539
6540
        /* make sure this wolfSSL object has arrays and rng setup. Protects
6541
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
6542
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
6543
            return ret;
6544
        }
6545
6546
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
6547
        if ((ssl->ConnectFilter != NULL) &&
6548
            (ssl->options.connectState == CONNECT_BEGIN)) {
6549
            wolfSSL_netfilter_decision_t res;
6550
            if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
6551
                 WOLFSSL_SUCCESS) &&
6552
                (res == WOLFSSL_NETFILTER_REJECT)) {
6553
                ssl->error = SOCKET_FILTERED_E;
6554
                WOLFSSL_ERROR(ssl->error);
6555
                return WOLFSSL_FATAL_ERROR;
6556
            }
6557
        }
6558
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
6559
6560
        if (ssl->options.side != WOLFSSL_CLIENT_END) {
6561
            ssl->error = SIDE_ERROR;
6562
            WOLFSSL_ERROR(ssl->error);
6563
            return WOLFSSL_FATAL_ERROR;
6564
        }
6565
6566
        #ifdef WOLFSSL_DTLS
6567
        if (ssl->version.major == DTLS_MAJOR) {
6568
            ssl->options.dtls   = 1;
6569
            ssl->options.tls    = 1;
6570
            ssl->options.tls1_1 = 1;
6571
            ssl->options.dtlsStateful = 1;
6572
        }
6573
        #endif
6574
6575
        /* fragOffset is non-zero when sending fragments. On the last
6576
         * fragment, fragOffset is zero again, and the state can be
6577
         * advanced. */
6578
        advanceState = ssl->fragOffset == 0 &&
6579
            (ssl->options.connectState == CONNECT_BEGIN ||
6580
             ssl->options.connectState == HELLO_AGAIN ||
6581
             (ssl->options.connectState >= FIRST_REPLY_DONE &&
6582
              ssl->options.connectState <= FIRST_REPLY_FOURTH));
6583
6584
#ifdef WOLFSSL_DTLS13
6585
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
6586
            advanceState = advanceState && !ssl->dtls13SendingAckOrRtx;
6587
#endif /* WOLFSSL_DTLS13 */
6588
6589
        if (ssl->buffers.outputBuffer.length > 0
6590
        #ifdef WOLFSSL_ASYNC_CRYPT
6591
            /* do not send buffered or advance state if last error was an
6592
                async pending operation */
6593
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
6594
        #endif
6595
        ) {
6596
            ret = SendBuffered(ssl);
6597
            if (ret == 0) {
6598
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
6599
                    if (advanceState) {
6600
                        ssl->options.connectState++;
6601
                        WOLFSSL_MSG("connect state: Advanced from last "
6602
                                    "buffered fragment send");
6603
                    #ifdef WOLFSSL_ASYNC_IO
6604
                        /* Cleanup async */
6605
                        FreeAsyncCtx(ssl, 0);
6606
                    #endif
6607
                    }
6608
                }
6609
                else {
6610
                    WOLFSSL_MSG("connect state: "
6611
                                "Not advanced, more fragments to send");
6612
                }
6613
            }
6614
            else {
6615
                ssl->error = ret;
6616
                WOLFSSL_ERROR(ssl->error);
6617
                return WOLFSSL_FATAL_ERROR;
6618
            }
6619
#ifdef WOLFSSL_DTLS13
6620
            if (ssl->options.dtls)
6621
                ssl->dtls13SendingAckOrRtx = 0;
6622
#endif /* WOLFSSL_DTLS13 */
6623
        }
6624
6625
        ret = RetrySendAlert(ssl);
6626
        if (ret != 0) {
6627
            ssl->error = ret;
6628
            WOLFSSL_ERROR(ssl->error);
6629
            return WOLFSSL_FATAL_ERROR;
6630
        }
6631
6632
        switch (ssl->options.connectState) {
6633
6634
        case CONNECT_BEGIN :
6635
            /* always send client hello first */
6636
            if ( (ssl->error = SendClientHello(ssl)) != 0) {
6637
                WOLFSSL_ERROR(ssl->error);
6638
                return WOLFSSL_FATAL_ERROR;
6639
            }
6640
            ssl->options.connectState = CLIENT_HELLO_SENT;
6641
            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
6642
            FALL_THROUGH;
6643
6644
        case CLIENT_HELLO_SENT :
6645
            neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
6646
                                          SERVER_HELLODONE_COMPLETE;
6647
            #ifdef WOLFSSL_DTLS
6648
                /* In DTLS, when resuming, we can go straight to FINISHED,
6649
                 * or do a cookie exchange and then skip to FINISHED, assume
6650
                 * we need the cookie exchange first. */
6651
                if (IsDtlsNotSctpMode(ssl))
6652
                    neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
6653
            #endif
6654
            /* get response */
6655
            WOLFSSL_MSG("Server state up to needed state.");
6656
            while (ssl->options.serverState < neededState) {
6657
                WOLFSSL_MSG("Progressing server state...");
6658
                #ifdef WOLFSSL_TLS13
6659
                    if (ssl->options.tls1_3)
6660
                        return wolfSSL_connect_TLSv13(ssl);
6661
                #endif
6662
                WOLFSSL_MSG("ProcessReply...");
6663
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
6664
                    WOLFSSL_ERROR(ssl->error);
6665
                    return WOLFSSL_FATAL_ERROR;
6666
                }
6667
                /* if resumption failed, reset needed state */
6668
                else if (neededState == SERVER_FINISHED_COMPLETE) {
6669
                    if (!ssl->options.resuming) {
6670
                    #ifdef WOLFSSL_DTLS
6671
                        if (IsDtlsNotSctpMode(ssl))
6672
                            neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
6673
                        else
6674
                    #endif
6675
                            neededState = SERVER_HELLODONE_COMPLETE;
6676
                    }
6677
                }
6678
                WOLFSSL_MSG("ProcessReply done.");
6679
6680
#ifdef WOLFSSL_DTLS13
6681
                if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)
6682
                    && ssl->dtls13Rtx.sendAcks == 1
6683
                    && ssl->options.seenUnifiedHdr) {
6684
                    /* we aren't negotiated the version yet, so we aren't sure
6685
                     * the other end can speak v1.3. On the other side we have
6686
                     * received a unified records, assuming that the
6687
                     * ServerHello got lost, we will send an empty ACK. In case
6688
                     * the server is a DTLS with version less than 1.3, it
6689
                     * should just ignore the message */
6690
                    ssl->dtls13Rtx.sendAcks = 0;
6691
                    if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
6692
                        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
6693
                            ssl->dtls13SendingAckOrRtx = 1;
6694
                        WOLFSSL_ERROR(ssl->error);
6695
                        return WOLFSSL_FATAL_ERROR;
6696
                    }
6697
                }
6698
#endif /* WOLFSSL_DTLS13 */
6699
            }
6700
6701
            ssl->options.connectState = HELLO_AGAIN;
6702
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
6703
            FALL_THROUGH;
6704
6705
        case HELLO_AGAIN :
6706
6707
        #ifdef WOLFSSL_TLS13
6708
            if (ssl->options.tls1_3)
6709
                return wolfSSL_connect_TLSv13(ssl);
6710
        #endif
6711
6712
            #ifdef WOLFSSL_DTLS
6713
            if (ssl->options.serverState ==
6714
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
6715
                if (IsDtlsNotSctpMode(ssl)) {
6716
                    /* re-init hashes, exclude first hello and verify request */
6717
                    if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
6718
                        WOLFSSL_ERROR(ssl->error);
6719
                        return WOLFSSL_FATAL_ERROR;
6720
                    }
6721
                    if ( (ssl->error = SendClientHello(ssl)) != 0) {
6722
                        WOLFSSL_ERROR(ssl->error);
6723
                        return WOLFSSL_FATAL_ERROR;
6724
                    }
6725
                }
6726
            }
6727
            #endif
6728
6729
            ssl->options.connectState = HELLO_AGAIN_REPLY;
6730
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
6731
            FALL_THROUGH;
6732
6733
        case HELLO_AGAIN_REPLY :
6734
            #ifdef WOLFSSL_DTLS
6735
                if (IsDtlsNotSctpMode(ssl)) {
6736
                    neededState = ssl->options.resuming ?
6737
                           SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
6738
6739
                    /* get response */
6740
                    while (ssl->options.serverState < neededState) {
6741
                        if ( (ssl->error = ProcessReply(ssl)) < 0) {
6742
                            WOLFSSL_ERROR(ssl->error);
6743
                            return WOLFSSL_FATAL_ERROR;
6744
                        }
6745
                        /* if resumption failed, reset needed state */
6746
                        if (neededState == SERVER_FINISHED_COMPLETE) {
6747
                            if (!ssl->options.resuming)
6748
                                neededState = SERVER_HELLODONE_COMPLETE;
6749
                        }
6750
                    }
6751
                }
6752
            #endif
6753
6754
            ssl->options.connectState = FIRST_REPLY_DONE;
6755
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
6756
            FALL_THROUGH;
6757
6758
        case FIRST_REPLY_DONE :
6759
            if (ssl->options.certOnly)
6760
                return WOLFSSL_SUCCESS;
6761
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
6762
                #ifdef WOLFSSL_TLS13
6763
                    if (ssl->options.tls1_3)
6764
                        return wolfSSL_connect_TLSv13(ssl);
6765
                #endif
6766
                if (ssl->options.sendVerify) {
6767
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
6768
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
6769
                        WOLFSSL_ERROR(ssl->error);
6770
                        return WOLFSSL_FATAL_ERROR;
6771
                    }
6772
                    WOLFSSL_MSG("sent: certificate");
6773
                }
6774
6775
            #endif
6776
            ssl->options.connectState = FIRST_REPLY_FIRST;
6777
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
6778
            FALL_THROUGH;
6779
6780
        case FIRST_REPLY_FIRST :
6781
        #ifdef WOLFSSL_TLS13
6782
            if (ssl->options.tls1_3)
6783
                return wolfSSL_connect_TLSv13(ssl);
6784
        #endif
6785
            if (!ssl->options.resuming) {
6786
                if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
6787
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
6788
#ifdef WOLFSSL_EXTRA_ALERTS
6789
                    if (ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY) ||
6790
                        ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) {
6791
                        SendAlert(ssl, alert_fatal, handshake_failure);
6792
                    }
6793
#endif
6794
                    WOLFSSL_ERROR(ssl->error);
6795
                    return WOLFSSL_FATAL_ERROR;
6796
                }
6797
                WOLFSSL_MSG("sent: client key exchange");
6798
            }
6799
6800
            ssl->options.connectState = FIRST_REPLY_SECOND;
6801
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
6802
            FALL_THROUGH;
6803
6804
    #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
6805
        case FIRST_REPLY_SECOND :
6806
            /* CLIENT: Fail-safe for Server Authentication. */
6807
            if (!ssl->options.peerAuthGood) {
6808
                WOLFSSL_MSG("Server authentication did not happen");
6809
                ssl->error = NO_PEER_VERIFY;
6810
                return WOLFSSL_FATAL_ERROR;
6811
            }
6812
6813
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
6814
                if (ssl->options.sendVerify) {
6815
                    if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
6816
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
6817
                        WOLFSSL_ERROR(ssl->error);
6818
                        return WOLFSSL_FATAL_ERROR;
6819
                    }
6820
                    WOLFSSL_MSG("sent: certificate verify");
6821
                }
6822
            #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
6823
            ssl->options.connectState = FIRST_REPLY_THIRD;
6824
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
6825
            FALL_THROUGH;
6826
6827
        case FIRST_REPLY_THIRD :
6828
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
6829
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
6830
                WOLFSSL_ERROR(ssl->error);
6831
                return WOLFSSL_FATAL_ERROR;
6832
            }
6833
            WOLFSSL_MSG("sent: change cipher spec");
6834
            ssl->options.connectState = FIRST_REPLY_FOURTH;
6835
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
6836
            FALL_THROUGH;
6837
6838
        case FIRST_REPLY_FOURTH :
6839
            if ( (ssl->error = SendFinished(ssl)) != 0) {
6840
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
6841
                WOLFSSL_ERROR(ssl->error);
6842
                return WOLFSSL_FATAL_ERROR;
6843
            }
6844
            WOLFSSL_MSG("sent: finished");
6845
            ssl->options.connectState = FINISHED_DONE;
6846
            WOLFSSL_MSG("connect state: FINISHED_DONE");
6847
            FALL_THROUGH;
6848
6849
#ifdef WOLFSSL_DTLS13
6850
        case WAIT_FINISHED_ACK:
6851
            ssl->options.connectState = FINISHED_DONE;
6852
            FALL_THROUGH;
6853
#endif /* WOLFSSL_DTLS13 */
6854
6855
        case FINISHED_DONE :
6856
            /* get response */
6857
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
6858
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
6859
                    WOLFSSL_ERROR(ssl->error);
6860
                    return WOLFSSL_FATAL_ERROR;
6861
                }
6862
6863
            ssl->options.connectState = SECOND_REPLY_DONE;
6864
            WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
6865
            FALL_THROUGH;
6866
6867
        case SECOND_REPLY_DONE:
6868
        #ifndef NO_HANDSHAKE_DONE_CB
6869
            if (ssl->hsDoneCb) {
6870
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
6871
                if (cbret < 0) {
6872
                    ssl->error = cbret;
6873
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
6874
                    return WOLFSSL_FATAL_ERROR;
6875
                }
6876
            }
6877
        #endif /* NO_HANDSHAKE_DONE_CB */
6878
6879
            if (!ssl->options.dtls) {
6880
                if (!ssl->options.keepResources) {
6881
                    FreeHandshakeResources(ssl);
6882
                }
6883
            }
6884
        #ifdef WOLFSSL_DTLS
6885
            else {
6886
                ssl->options.dtlsHsRetain = 1;
6887
            }
6888
        #endif /* WOLFSSL_DTLS */
6889
6890
        #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
6891
            /* This may be necessary in async so that we don't try to
6892
             * renegotiate again */
6893
            if (ssl->secure_renegotiation &&
6894
                    ssl->secure_renegotiation->startScr) {
6895
                ssl->secure_renegotiation->startScr = 0;
6896
            }
6897
        #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
6898
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
6899
            /* Free the remaining async context if not using it for crypto */
6900
            FreeAsyncCtx(ssl, 1);
6901
        #endif
6902
6903
            ssl->error = 0; /* clear the error */
6904
6905
            WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
6906
            return WOLFSSL_SUCCESS;
6907
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
6908
6909
        default:
6910
            WOLFSSL_MSG("Unknown connect state ERROR");
6911
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
6912
        }
6913
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
6914
    }
6915
6916
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
6917
/* end client only parts */
6918
6919
/* server only parts */
6920
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
6921
6922
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
6923
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
6924
    {
6925
        WOLFSSL_STUB("wolfSSLv2_server_method");
6926
        return 0;
6927
    }
6928
    #endif
6929
6930
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
6931
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
6932
    {
6933
        return wolfSSLv3_server_method_ex(NULL);
6934
    }
6935
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
6936
    {
6937
        WOLFSSL_METHOD* method =
6938
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
6939
                                                     heap, DYNAMIC_TYPE_METHOD);
6940
        (void)heap;
6941
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
6942
        if (method) {
6943
            InitSSL_Method(method, MakeSSLv3());
6944
            method->side = WOLFSSL_SERVER_END;
6945
        }
6946
        return method;
6947
    }
6948
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
6949
6950
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
6951
0
    {
6952
0
        return wolfSSLv23_server_method_ex(NULL);
6953
0
    }
6954
6955
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
6956
0
    {
6957
0
        WOLFSSL_METHOD* method =
6958
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
6959
0
                                                     heap, DYNAMIC_TYPE_METHOD);
6960
0
        (void)heap;
6961
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
6962
0
        if (method) {
6963
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
6964
0
        defined(WOLFSSL_SHA512)
6965
0
        #ifdef WOLFSSL_TLS13
6966
0
            InitSSL_Method(method, MakeTLSv1_3());
6967
        #elif !defined(WOLFSSL_NO_TLS12)
6968
            InitSSL_Method(method, MakeTLSv1_2());
6969
        #elif !defined(NO_OLD_TLS)
6970
            InitSSL_Method(method, MakeTLSv1_1());
6971
        #endif
6972
    #else
6973
        #ifndef NO_OLD_TLS
6974
            InitSSL_Method(method, MakeTLSv1_1());
6975
        #else
6976
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
6977
        #endif
6978
    #endif
6979
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
6980
0
            method->downgrade = 1;
6981
0
    #endif
6982
0
            method->side      = WOLFSSL_SERVER_END;
6983
0
        }
6984
0
        return method;
6985
0
    }
6986
6987
6988
    WOLFSSL_ABI
6989
    int wolfSSL_accept(WOLFSSL* ssl)
6990
    {
6991
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
6992
    defined(WOLFSSL_TLS13))
6993
        word16 havePSK = 0;
6994
        word16 haveAnon = 0;
6995
        word16 haveMcast = 0;
6996
#endif
6997
        int ret = 0;
6998
6999
        (void)ret;
7000
7001
        if (ssl == NULL)
7002
            return WOLFSSL_FATAL_ERROR;
7003
7004
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
7005
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
7006
            WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
7007
            ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
7008
            if (ssl->error != WOLFSSL_SUCCESS) {
7009
                WOLFSSL_ERROR(ssl->error);
7010
                return WOLFSSL_FATAL_ERROR;
7011
            }
7012
            ssl->error = 0; /* expected to be zero here */
7013
        }
7014
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
7015
7016
#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
7017
        return wolfSSL_accept_TLSv13(ssl);
7018
#else
7019
    #ifdef WOLFSSL_TLS13
7020
        if (ssl->options.tls1_3)
7021
            return wolfSSL_accept_TLSv13(ssl);
7022
    #endif
7023
        WOLFSSL_ENTER("wolfSSL_accept");
7024
7025
        /* make sure this wolfSSL object has arrays and rng setup. Protects
7026
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
7027
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
7028
            return ret;
7029
        }
7030
7031
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
7032
        if ((ssl->AcceptFilter != NULL) &&
7033
            ((ssl->options.acceptState == ACCEPT_BEGIN)
7034
#ifdef HAVE_SECURE_RENEGOTIATION
7035
             || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
7036
#endif
7037
                ))
7038
        {
7039
            wolfSSL_netfilter_decision_t res;
7040
            if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
7041
                 WOLFSSL_SUCCESS) &&
7042
                (res == WOLFSSL_NETFILTER_REJECT)) {
7043
                ssl->error = SOCKET_FILTERED_E;
7044
                WOLFSSL_ERROR(ssl->error);
7045
                return WOLFSSL_FATAL_ERROR;
7046
            }
7047
        }
7048
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
7049
7050
        #ifdef HAVE_ERRNO_H
7051
            errno = 0;
7052
        #endif
7053
7054
        #ifndef NO_PSK
7055
            havePSK = ssl->options.havePSK;
7056
        #endif
7057
        (void)havePSK;
7058
7059
        #ifdef HAVE_ANON
7060
            haveAnon = ssl->options.useAnon;
7061
        #endif
7062
        (void)haveAnon;
7063
7064
        #ifdef WOLFSSL_MULTICAST
7065
            haveMcast = ssl->options.haveMcast;
7066
        #endif
7067
        (void)haveMcast;
7068
7069
        if (ssl->options.side != WOLFSSL_SERVER_END) {
7070
            ssl->error = SIDE_ERROR;
7071
            WOLFSSL_ERROR(ssl->error);
7072
            return WOLFSSL_FATAL_ERROR;
7073
        }
7074
7075
    #ifndef NO_CERTS
7076
        /* in case used set_accept_state after init */
7077
        if (!havePSK && !haveAnon && !haveMcast) {
7078
        #ifdef WOLFSSL_CERT_SETUP_CB
7079
            if (ssl->ctx->certSetupCb != NULL) {
7080
                WOLFSSL_MSG("CertSetupCb set. server cert and "
7081
                            "key not checked");
7082
            }
7083
            else
7084
        #endif
7085
            {
7086
                if (!ssl->buffers.certificate ||
7087
                    !ssl->buffers.certificate->buffer) {
7088
7089
                    WOLFSSL_MSG("accept error: server cert required");
7090
                    ssl->error = NO_PRIVATE_KEY;
7091
                    WOLFSSL_ERROR(ssl->error);
7092
                    return WOLFSSL_FATAL_ERROR;
7093
                }
7094
7095
                if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
7096
                    /* allow no private key if using existing key */
7097
                #ifdef WOLF_PRIVATE_KEY_ID
7098
                    if (ssl->devId != INVALID_DEVID
7099
                    #ifdef HAVE_PK_CALLBACKS
7100
                        || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
7101
                    #endif
7102
                    ) {
7103
                        WOLFSSL_MSG("Allowing no server private key "
7104
                                    "(external)");
7105
                    }
7106
                    else
7107
                #endif
7108
                    {
7109
                        WOLFSSL_MSG("accept error: server key required");
7110
                        ssl->error = NO_PRIVATE_KEY;
7111
                        WOLFSSL_ERROR(ssl->error);
7112
                        return WOLFSSL_FATAL_ERROR;
7113
                    }
7114
                }
7115
            }
7116
        }
7117
    #endif
7118
7119
    #ifdef WOLFSSL_DTLS
7120
        if (ssl->version.major == DTLS_MAJOR) {
7121
            ssl->options.dtls   = 1;
7122
            ssl->options.tls    = 1;
7123
            ssl->options.tls1_1 = 1;
7124
            if (!IsDtlsNotSctpMode(ssl) || IsSCR(ssl))
7125
                ssl->options.dtlsStateful = 1;
7126
        }
7127
    #endif
7128
7129
        if (ssl->buffers.outputBuffer.length > 0
7130
        #ifdef WOLFSSL_ASYNC_CRYPT
7131
            /* do not send buffered or advance state if last error was an
7132
                async pending operation */
7133
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
7134
        #endif
7135
        ) {
7136
            ret = SendBuffered(ssl);
7137
            if (ret == 0) {
7138
                /* fragOffset is non-zero when sending fragments. On the last
7139
                 * fragment, fragOffset is zero again, and the state can be
7140
                 * advanced. */
7141
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
7142
                    if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE ||
7143
                        ssl->options.acceptState == SERVER_HELLO_SENT ||
7144
                        ssl->options.acceptState == CERT_SENT ||
7145
                        ssl->options.acceptState == CERT_STATUS_SENT ||
7146
                        ssl->options.acceptState == KEY_EXCHANGE_SENT ||
7147
                        ssl->options.acceptState == CERT_REQ_SENT ||
7148
                        ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE ||
7149
                        ssl->options.acceptState == TICKET_SENT ||
7150
                        ssl->options.acceptState == CHANGE_CIPHER_SENT) {
7151
                        ssl->options.acceptState++;
7152
                        WOLFSSL_MSG("accept state: Advanced from last "
7153
                                    "buffered fragment send");
7154
                    #ifdef WOLFSSL_ASYNC_IO
7155
                        /* Cleanup async */
7156
                        FreeAsyncCtx(ssl, 0);
7157
                    #endif
7158
                    }
7159
                }
7160
                else {
7161
                    WOLFSSL_MSG("accept state: "
7162
                                "Not advanced, more fragments to send");
7163
                }
7164
            }
7165
            else {
7166
                ssl->error = ret;
7167
                WOLFSSL_ERROR(ssl->error);
7168
                return WOLFSSL_FATAL_ERROR;
7169
            }
7170
#ifdef WOLFSSL_DTLS13
7171
            if (ssl->options.dtls)
7172
                ssl->dtls13SendingAckOrRtx = 0;
7173
#endif /* WOLFSSL_DTLS13 */
7174
        }
7175
7176
        ret = RetrySendAlert(ssl);
7177
        if (ret != 0) {
7178
            ssl->error = ret;
7179
            WOLFSSL_ERROR(ssl->error);
7180
            return WOLFSSL_FATAL_ERROR;
7181
        }
7182
7183
        switch (ssl->options.acceptState) {
7184
7185
        case ACCEPT_BEGIN :
7186
#ifdef HAVE_SECURE_RENEGOTIATION
7187
        case ACCEPT_BEGIN_RENEG:
7188
#endif
7189
            /* get response */
7190
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
7191
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
7192
                    WOLFSSL_ERROR(ssl->error);
7193
                    return WOLFSSL_FATAL_ERROR;
7194
                }
7195
#ifdef WOLFSSL_TLS13
7196
            ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
7197
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
7198
            FALL_THROUGH;
7199
7200
        case ACCEPT_CLIENT_HELLO_DONE :
7201
            if (ssl->options.tls1_3) {
7202
                return wolfSSL_accept_TLSv13(ssl);
7203
            }
7204
#endif
7205
7206
            ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
7207
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
7208
            FALL_THROUGH;
7209
7210
        case ACCEPT_FIRST_REPLY_DONE :
7211
            if (ssl->options.returnOnGoodCh) {
7212
                /* Higher level in stack wants us to return. Simulate a
7213
                 * WANT_WRITE to accomplish this. */
7214
                ssl->error = WANT_WRITE;
7215
                return WOLFSSL_FATAL_ERROR;
7216
            }
7217
            if ( (ssl->error = SendServerHello(ssl)) != 0) {
7218
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7219
                WOLFSSL_ERROR(ssl->error);
7220
                return WOLFSSL_FATAL_ERROR;
7221
            }
7222
            ssl->options.acceptState = SERVER_HELLO_SENT;
7223
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
7224
            FALL_THROUGH;
7225
7226
        case SERVER_HELLO_SENT :
7227
        #ifdef WOLFSSL_TLS13
7228
            if (ssl->options.tls1_3) {
7229
                return wolfSSL_accept_TLSv13(ssl);
7230
            }
7231
        #endif
7232
            #ifndef NO_CERTS
7233
                if (!ssl->options.resuming)
7234
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
7235
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7236
                        WOLFSSL_ERROR(ssl->error);
7237
                        return WOLFSSL_FATAL_ERROR;
7238
                    }
7239
            #endif
7240
            ssl->options.acceptState = CERT_SENT;
7241
            WOLFSSL_MSG("accept state CERT_SENT");
7242
            FALL_THROUGH;
7243
7244
        case CERT_SENT :
7245
            #ifndef NO_CERTS
7246
            if (!ssl->options.resuming)
7247
                if ( (ssl->error = SendCertificateStatus(ssl)) != 0) {
7248
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7249
                    WOLFSSL_ERROR(ssl->error);
7250
                    return WOLFSSL_FATAL_ERROR;
7251
                }
7252
            #endif
7253
            ssl->options.acceptState = CERT_STATUS_SENT;
7254
            WOLFSSL_MSG("accept state CERT_STATUS_SENT");
7255
            FALL_THROUGH;
7256
7257
        case CERT_STATUS_SENT :
7258
        #ifdef WOLFSSL_TLS13
7259
            if (ssl->options.tls1_3) {
7260
                return wolfSSL_accept_TLSv13(ssl);
7261
            }
7262
        #endif
7263
            if (!ssl->options.resuming)
7264
                if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
7265
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7266
                    WOLFSSL_ERROR(ssl->error);
7267
                    return WOLFSSL_FATAL_ERROR;
7268
                }
7269
            ssl->options.acceptState = KEY_EXCHANGE_SENT;
7270
            WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
7271
            FALL_THROUGH;
7272
7273
        case KEY_EXCHANGE_SENT :
7274
            #ifndef NO_CERTS
7275
                if (!ssl->options.resuming) {
7276
                    if (ssl->options.verifyPeer) {
7277
                        if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
7278
                            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7279
                            WOLFSSL_ERROR(ssl->error);
7280
                            return WOLFSSL_FATAL_ERROR;
7281
                        }
7282
                    }
7283
                    else {
7284
                        /* SERVER: Peer auth good if not verifying client. */
7285
                        ssl->options.peerAuthGood = 1;
7286
                    }
7287
                }
7288
            #endif
7289
            ssl->options.acceptState = CERT_REQ_SENT;
7290
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
7291
            FALL_THROUGH;
7292
7293
        case CERT_REQ_SENT :
7294
            if (!ssl->options.resuming)
7295
                if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
7296
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7297
                    WOLFSSL_ERROR(ssl->error);
7298
                    return WOLFSSL_FATAL_ERROR;
7299
                }
7300
            ssl->options.acceptState = SERVER_HELLO_DONE;
7301
            WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
7302
            FALL_THROUGH;
7303
7304
        case SERVER_HELLO_DONE :
7305
            if (!ssl->options.resuming) {
7306
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
7307
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
7308
                        WOLFSSL_ERROR(ssl->error);
7309
                        return WOLFSSL_FATAL_ERROR;
7310
                    }
7311
            }
7312
            ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
7313
            WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
7314
            FALL_THROUGH;
7315
7316
        case ACCEPT_SECOND_REPLY_DONE :
7317
        #ifndef NO_CERTS
7318
            /* SERVER: When not resuming and verifying peer but no certificate
7319
             * received and not failing when not received then peer auth good.
7320
             */
7321
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
7322
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
7323
                ssl->options.peerAuthGood = 1;
7324
            }
7325
        #endif /* !NO_CERTS  */
7326
        #ifdef WOLFSSL_NO_CLIENT_AUTH
7327
            if (!ssl->options.resuming) {
7328
                ssl->options.peerAuthGood = 1;
7329
            }
7330
        #endif
7331
7332
#ifdef HAVE_SESSION_TICKET
7333
            if (ssl->options.createTicket && !ssl->options.noTicketTls12) {
7334
                if ( (ssl->error = SendTicket(ssl)) != 0) {
7335
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7336
                    WOLFSSL_MSG("Thought we need ticket but failed");
7337
                    WOLFSSL_ERROR(ssl->error);
7338
                    return WOLFSSL_FATAL_ERROR;
7339
                }
7340
            }
7341
#endif /* HAVE_SESSION_TICKET */
7342
            ssl->options.acceptState = TICKET_SENT;
7343
            WOLFSSL_MSG("accept state  TICKET_SENT");
7344
            FALL_THROUGH;
7345
7346
        case TICKET_SENT:
7347
            /* SERVER: Fail-safe for CLient Authentication. */
7348
            if (!ssl->options.peerAuthGood) {
7349
                WOLFSSL_MSG("Client authentication did not happen");
7350
                return WOLFSSL_FATAL_ERROR;
7351
            }
7352
7353
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
7354
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7355
                WOLFSSL_ERROR(ssl->error);
7356
                return WOLFSSL_FATAL_ERROR;
7357
            }
7358
            ssl->options.acceptState = CHANGE_CIPHER_SENT;
7359
            WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
7360
            FALL_THROUGH;
7361
7362
        case CHANGE_CIPHER_SENT :
7363
            if ( (ssl->error = SendFinished(ssl)) != 0) {
7364
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
7365
                WOLFSSL_ERROR(ssl->error);
7366
                return WOLFSSL_FATAL_ERROR;
7367
            }
7368
7369
            ssl->options.acceptState = ACCEPT_FINISHED_DONE;
7370
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
7371
            FALL_THROUGH;
7372
7373
        case ACCEPT_FINISHED_DONE :
7374
            if (ssl->options.resuming) {
7375
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
7376
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
7377
                        WOLFSSL_ERROR(ssl->error);
7378
                        return WOLFSSL_FATAL_ERROR;
7379
                    }
7380
                }
7381
            }
7382
            ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
7383
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
7384
            FALL_THROUGH;
7385
7386
        case ACCEPT_THIRD_REPLY_DONE :
7387
#ifndef NO_HANDSHAKE_DONE_CB
7388
            if (ssl->hsDoneCb) {
7389
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
7390
                if (cbret < 0) {
7391
                    ssl->error = cbret;
7392
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
7393
                    return WOLFSSL_FATAL_ERROR;
7394
                }
7395
            }
7396
#endif /* NO_HANDSHAKE_DONE_CB */
7397
7398
            if (!ssl->options.dtls) {
7399
                if (!ssl->options.keepResources) {
7400
                    FreeHandshakeResources(ssl);
7401
                }
7402
            }
7403
#ifdef WOLFSSL_DTLS
7404
            else {
7405
                ssl->options.dtlsHsRetain = 1;
7406
            }
7407
#endif /* WOLFSSL_DTLS */
7408
7409
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
7410
            /* This may be necessary in async so that we don't try to
7411
             * renegotiate again */
7412
            if (ssl->secure_renegotiation &&
7413
                    ssl->secure_renegotiation->startScr) {
7414
                ssl->secure_renegotiation->startScr = 0;
7415
            }
7416
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
7417
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
7418
            /* Free the remaining async context if not using it for crypto */
7419
            FreeAsyncCtx(ssl, 1);
7420
#endif
7421
7422
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
7423
            if (ssl->dtls_export) {
7424
                if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
7425
                    WOLFSSL_MSG("Export DTLS session error");
7426
                    WOLFSSL_ERROR(ssl->error);
7427
                    return WOLFSSL_FATAL_ERROR;
7428
                }
7429
            }
7430
#endif
7431
            ssl->error = 0; /* clear the error */
7432
7433
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
7434
            return WOLFSSL_SUCCESS;
7435
7436
        default:
7437
            WOLFSSL_MSG("Unknown accept state ERROR");
7438
            return WOLFSSL_FATAL_ERROR;
7439
        }
7440
#endif /* !WOLFSSL_NO_TLS12 */
7441
    }
7442
7443
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
7444
/* end server only parts */
7445
7446
7447
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
7448
struct chGoodDisableReadCbCtx {
7449
    ClientHelloGoodCb userCb;
7450
    void*             userCtx;
7451
};
7452
7453
static int chGoodDisableReadCB(WOLFSSL* ssl, void* ctx)
7454
{
7455
    struct chGoodDisableReadCbCtx* cb = (struct chGoodDisableReadCbCtx*)ctx;
7456
    int ret = 0;
7457
    if (cb->userCb != NULL)
7458
        ret = cb->userCb(ssl, cb->userCtx);
7459
    if (ret >= 0)
7460
        wolfSSL_SSLDisableRead(ssl);
7461
    return ret;
7462
}
7463
7464
/**
7465
 * Statelessly listen for a connection
7466
 * @param ssl The ssl object to use for listening to connections
7467
 * @return WOLFSSL_SUCCESS - ClientHello containing a valid cookie was received
7468
 *                           The connection can be continued with wolfSSL_accept
7469
 *         WOLFSSL_FAILURE - The I/O layer returned WANT_READ. This is either
7470
 *                           because there is no data to read and we are using
7471
 *                           non-blocking sockets or we sent a cookie request
7472
 *                           and we are waiting for a reply. The user should
7473
 *                           call wolfDTLS_accept_stateless again after data
7474
 *                           becomes available in the I/O layer.
7475
 *         WOLFSSL_FATAL_ERROR - A fatal error occurred. The ssl object should
7476
 *                           be free'd and allocated again to continue.
7477
 */
7478
int wolfDTLS_accept_stateless(WOLFSSL* ssl)
7479
{
7480
    byte disableRead;
7481
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
7482
    struct chGoodDisableReadCbCtx cb;
7483
7484
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
7485
7486
    if (ssl == NULL)
7487
        return WOLFSSL_FATAL_ERROR;
7488
7489
    /* Save this to restore it later */
7490
    disableRead = (byte)ssl->options.disableRead;
7491
    cb.userCb = ssl->chGoodCb;
7492
    cb.userCtx = ssl->chGoodCtx;
7493
7494
    /* Register our own callback so that we can disable reading */
7495
    if (wolfDTLS_SetChGoodCb(ssl, chGoodDisableReadCB, &cb) != WOLFSSL_SUCCESS)
7496
        return WOLFSSL_FATAL_ERROR;
7497
7498
    ssl->options.returnOnGoodCh = 1;
7499
    ret = wolfSSL_accept(ssl);
7500
    ssl->options.returnOnGoodCh = 0;
7501
    /* restore user options */
7502
    ssl->options.disableRead = disableRead;
7503
    (void)wolfDTLS_SetChGoodCb(ssl, cb.userCb, cb.userCtx);
7504
    if (ret == WOLFSSL_SUCCESS) {
7505
        WOLFSSL_MSG("should not happen. maybe the user called "
7506
                    "wolfDTLS_accept_stateless instead of wolfSSL_accept");
7507
    }
7508
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_READ) ||
7509
             ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
7510
        ssl->error = 0;
7511
        if (ssl->options.dtlsStateful)
7512
            ret = WOLFSSL_SUCCESS;
7513
        else
7514
            ret = WOLFSSL_FAILURE;
7515
    }
7516
    else {
7517
        ret = WOLFSSL_FATAL_ERROR;
7518
    }
7519
    return ret;
7520
}
7521
7522
int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx)
7523
{
7524
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
7525
7526
    if (ssl == NULL)
7527
        return BAD_FUNC_ARG;
7528
7529
    ssl->chGoodCb  = cb;
7530
    ssl->chGoodCtx = user_ctx;
7531
7532
    return WOLFSSL_SUCCESS;
7533
}
7534
#endif
7535
7536
#ifndef NO_HANDSHAKE_DONE_CB
7537
7538
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
7539
0
{
7540
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
7541
7542
0
    if (ssl == NULL)
7543
0
        return BAD_FUNC_ARG;
7544
7545
0
    ssl->hsDoneCb  = cb;
7546
0
    ssl->hsDoneCtx = user_ctx;
7547
7548
0
    return WOLFSSL_SUCCESS;
7549
0
}
7550
7551
#endif /* NO_HANDSHAKE_DONE_CB */
7552
7553
WOLFSSL_ABI
7554
int wolfSSL_Cleanup(void)
7555
22.9k
{
7556
22.9k
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
7557
22.9k
    int release = 0;
7558
22.9k
#if !defined(NO_SESSION_CACHE)
7559
22.9k
    int i;
7560
22.9k
    int j;
7561
22.9k
#endif
7562
7563
22.9k
    WOLFSSL_ENTER("wolfSSL_Cleanup");
7564
7565
#ifndef WOLFSSL_MUTEX_INITIALIZER
7566
    if (inits_count_mutex_valid == 1) {
7567
#endif
7568
22.9k
        if (wc_LockMutex(&inits_count_mutex) != 0) {
7569
0
            WOLFSSL_MSG("Bad Lock Mutex count");
7570
0
            return BAD_MUTEX_E;
7571
0
        }
7572
#ifndef WOLFSSL_MUTEX_INITIALIZER
7573
    }
7574
#endif
7575
7576
22.9k
    if (initRefCount > 0) {
7577
5.25k
        initRefCount = initRefCount - 1;
7578
5.25k
        if (initRefCount == 0)
7579
5.25k
            release = 1;
7580
5.25k
    }
7581
7582
#ifndef WOLFSSL_MUTEX_INITIALIZER
7583
    if (inits_count_mutex_valid == 1) {
7584
#endif
7585
22.9k
        wc_UnLockMutex(&inits_count_mutex);
7586
#ifndef WOLFSSL_MUTEX_INITIALIZER
7587
    }
7588
#endif
7589
7590
22.9k
    if (!release)
7591
17.7k
        return ret;
7592
7593
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
7594
    wolfSSL_crypto_policy_disable();
7595
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
7596
7597
#ifdef OPENSSL_EXTRA
7598
    wolfSSL_BN_free_one();
7599
#endif
7600
7601
5.25k
#ifndef NO_SESSION_CACHE
7602
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
7603
    for (i = 0; i < SESSION_ROWS; ++i) {
7604
        if ((SessionCache[i].lock_valid == 1) &&
7605
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
7606
            if (ret == WOLFSSL_SUCCESS)
7607
                ret = BAD_MUTEX_E;
7608
        }
7609
        SessionCache[i].lock_valid = 0;
7610
    }
7611
    #else
7612
5.25k
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
7613
0
        if (ret == WOLFSSL_SUCCESS)
7614
0
            ret = BAD_MUTEX_E;
7615
0
    }
7616
5.25k
    session_lock_valid = 0;
7617
5.25k
    #endif
7618
63.0k
    for (i = 0; i < SESSION_ROWS; i++) {
7619
231k
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
7620
    #ifdef SESSION_CACHE_DYNAMIC_MEM
7621
            if (SessionCache[i].Sessions[j]) {
7622
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
7623
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
7624
                      DYNAMIC_TYPE_SESSION);
7625
                SessionCache[i].Sessions[j] = NULL;
7626
            }
7627
    #else
7628
173k
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
7629
173k
    #endif
7630
173k
        }
7631
57.7k
    }
7632
5.25k
    #ifndef NO_CLIENT_CACHE
7633
    #ifndef WOLFSSL_MUTEX_INITIALIZER
7634
    if ((clisession_mutex_valid == 1) &&
7635
        (wc_FreeMutex(&clisession_mutex) != 0)) {
7636
        if (ret == WOLFSSL_SUCCESS)
7637
            ret = BAD_MUTEX_E;
7638
    }
7639
    clisession_mutex_valid = 0;
7640
    #endif
7641
5.25k
    #endif
7642
5.25k
#endif /* !NO_SESSION_CACHE */
7643
7644
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
7645
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
7646
    if ((inits_count_mutex_valid == 1) &&
7647
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
7648
        if (ret == WOLFSSL_SUCCESS)
7649
            ret = BAD_MUTEX_E;
7650
    }
7651
    inits_count_mutex_valid = 0;
7652
#endif
7653
7654
#ifdef OPENSSL_EXTRA
7655
    wolfSSL_RAND_Cleanup();
7656
#endif
7657
7658
5.25k
    if (wolfCrypt_Cleanup() != 0) {
7659
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
7660
0
        if (ret == WOLFSSL_SUCCESS)
7661
0
            ret = WC_CLEANUP_E;
7662
0
    }
7663
7664
#if FIPS_VERSION_GE(5,1)
7665
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
7666
        if (ret == WOLFSSL_SUCCESS)
7667
            ret = WC_CLEANUP_E;
7668
    }
7669
#endif
7670
7671
5.25k
#ifdef HAVE_GLOBAL_RNG
7672
#ifndef WOLFSSL_MUTEX_INITIALIZER
7673
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
7674
        if (ret == WOLFSSL_SUCCESS)
7675
            ret = BAD_MUTEX_E;
7676
    }
7677
    globalRNGMutex_valid = 0;
7678
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
7679
7680
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
7681
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
7682
    gDrbgDefCtx = NULL;
7683
    #endif
7684
5.25k
#endif
7685
7686
#ifdef HAVE_EX_DATA_CRYPTO
7687
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
7688
    crypto_ex_cb_ctx_session = NULL;
7689
#endif
7690
7691
#ifdef WOLFSSL_MEM_FAIL_COUNT
7692
    wc_MemFailCount_Free();
7693
#endif
7694
7695
5.25k
    return ret;
7696
22.9k
}
7697
7698
7699
/* call before SSL_connect, if verifying will add name check to
7700
   date check and signature check */
7701
WOLFSSL_ABI
7702
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
7703
0
{
7704
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
7705
7706
0
    if (ssl == NULL || dn == NULL) {
7707
0
        WOLFSSL_MSG("Bad function argument: NULL");
7708
0
        return WOLFSSL_FAILURE;
7709
0
    }
7710
7711
0
    if (ssl->buffers.domainName.buffer)
7712
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
7713
7714
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
7715
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
7716
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
7717
7718
0
    if (ssl->buffers.domainName.buffer) {
7719
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
7720
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
7721
0
        domainName[ssl->buffers.domainName.length] = '\0';
7722
0
        return WOLFSSL_SUCCESS;
7723
0
    }
7724
0
    else {
7725
0
        ssl->error = MEMORY_ERROR;
7726
0
        return WOLFSSL_FAILURE;
7727
0
    }
7728
0
}
7729
7730
/* call before SSL_connect, if verifying will add IP SAN check to
7731
   date check and signature check */
7732
WOLFSSL_ABI
7733
int wolfSSL_check_ip_address(WOLFSSL* ssl, const char* ipaddr)
7734
0
{
7735
0
    WOLFSSL_ENTER("wolfSSL_check_ip_address");
7736
7737
0
    if (ssl == NULL || ipaddr == NULL) {
7738
0
        WOLFSSL_MSG("Bad function argument: NULL");
7739
0
        return WOLFSSL_FAILURE;
7740
0
    }
7741
7742
0
    if (ssl->buffers.ipasc.buffer != NULL) {
7743
0
        XFREE(ssl->buffers.ipasc.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
7744
0
        ssl->buffers.ipasc.buffer = NULL;
7745
0
        ssl->buffers.ipasc.length = 0;
7746
0
    }
7747
7748
0
    ssl->buffers.ipasc.length = (word32)XSTRLEN(ipaddr);
7749
0
    ssl->buffers.ipasc.buffer = (byte*)XMALLOC(ssl->buffers.ipasc.length + 1,
7750
0
                                               ssl->heap, DYNAMIC_TYPE_DOMAIN);
7751
0
    if (ssl->buffers.ipasc.buffer == NULL) {
7752
0
        ssl->error = MEMORY_ERROR;
7753
0
        return WOLFSSL_FAILURE;
7754
0
    }
7755
7756
0
    XMEMCPY(ssl->buffers.ipasc.buffer, ipaddr, ssl->buffers.ipasc.length);
7757
0
    ssl->buffers.ipasc.buffer[ssl->buffers.ipasc.length] = '\0';
7758
7759
#ifdef OPENSSL_EXTRA
7760
    if (ssl->param == NULL) {
7761
        return WOLFSSL_FAILURE;
7762
    }
7763
    if (wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(ssl->param, ipaddr) !=
7764
            WOLFSSL_SUCCESS) {
7765
        return WOLFSSL_FAILURE;
7766
    }
7767
#endif
7768
7769
0
    return WOLFSSL_SUCCESS;
7770
0
}
7771
7772
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
7773
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
7774
    if (ssl == NULL) {
7775
        return NULL;
7776
    }
7777
7778
    if (ssl->buffers.domainName.buffer)
7779
        return (const char *)ssl->buffers.domainName.buffer;
7780
    else if (ssl->session && ssl->session->peer)
7781
        return ssl->session->peer->subjectCN;
7782
#ifdef KEEP_PEER_CERT
7783
    else if (ssl->peerCert.subjectCN[0])
7784
        return ssl->peerCert.subjectCN;
7785
#endif
7786
    else {
7787
        ssl->error = NO_PEER_CERT;
7788
        return NULL;
7789
    }
7790
}
7791
7792
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
7793
7794
/* turn on wolfSSL zlib compression
7795
   returns WOLFSSL_SUCCESS for success, else error (not built in)
7796
*/
7797
int wolfSSL_set_compression(WOLFSSL* ssl)
7798
0
{
7799
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
7800
0
    (void)ssl;
7801
#ifdef HAVE_LIBZ
7802
    ssl->options.usingCompression = 1;
7803
    return WOLFSSL_SUCCESS;
7804
#else
7805
0
    return NOT_COMPILED_IN;
7806
0
#endif
7807
0
}
7808
7809
7810
#ifndef USE_WINDOWS_API
7811
    #if !defined(NO_WRITEV) && !defined(NO_TLS)
7812
7813
        /* simulate writev semantics, doesn't actually do block at a time though
7814
           because of SSL_write behavior and because front adds may be small */
7815
        int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt)
7816
0
        {
7817
0
        #ifdef WOLFSSL_SMALL_STACK
7818
0
            byte   staticBuffer[1]; /* force heap usage */
7819
        #else
7820
            byte   staticBuffer[FILE_BUFFER_SIZE];
7821
        #endif
7822
0
            byte* myBuffer  = staticBuffer;
7823
0
            int   dynamic   = 0;
7824
0
            size_t sending   = 0;
7825
0
            size_t idx       = 0;
7826
0
            int   i;
7827
0
            int   ret;
7828
7829
0
            WOLFSSL_ENTER("wolfSSL_writev");
7830
7831
0
            for (i = 0; i < iovcnt; i++)
7832
0
                if (! WC_SAFE_SUM_UNSIGNED(size_t, sending, iov[i].iov_len,
7833
0
                                           sending))
7834
0
                    return BUFFER_E;
7835
7836
0
            if (sending > sizeof(staticBuffer)) {
7837
0
                myBuffer = (byte*)XMALLOC(sending, ssl->heap,
7838
0
                                          DYNAMIC_TYPE_WRITEV);
7839
0
                if (!myBuffer)
7840
0
                    return MEMORY_ERROR;
7841
7842
0
                dynamic = 1;
7843
0
            }
7844
7845
0
            for (i = 0; i < iovcnt; i++) {
7846
0
                XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
7847
0
                idx += (int)iov[i].iov_len;
7848
0
            }
7849
7850
           /* myBuffer may not be initialized fully, but the span up to the
7851
            * sending length will be.
7852
            */
7853
0
            PRAGMA_GCC_DIAG_PUSH
7854
0
            PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
7855
0
            ret = wolfSSL_write_internal(ssl, myBuffer, sending);
7856
0
            PRAGMA_GCC_DIAG_POP
7857
7858
0
            if (dynamic)
7859
0
                XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
7860
7861
0
            return ret;
7862
0
        }
7863
    #endif
7864
#endif
7865
7866
7867
#ifdef WOLFSSL_CALLBACKS
7868
7869
    typedef struct itimerval Itimerval;
7870
7871
    /* don't keep calling simple functions while setting up timer and signals
7872
       if no inlining these are the next best */
7873
7874
    #define AddTimes(a, b, c)                       \
7875
        do {                                        \
7876
            (c).tv_sec  = (a).tv_sec + (b).tv_sec;  \
7877
            (c).tv_usec = (a).tv_usec + (b).tv_usec;\
7878
            if ((c).tv_usec >=  1000000) {          \
7879
                (c).tv_sec++;                       \
7880
                (c).tv_usec -= 1000000;             \
7881
            }                                       \
7882
        } while (0)
7883
7884
7885
    #define SubtractTimes(a, b, c)                  \
7886
        do {                                        \
7887
            (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
7888
            (c).tv_usec = (a).tv_usec - (b).tv_usec;\
7889
            if ((c).tv_usec < 0) {                  \
7890
                (c).tv_sec--;                       \
7891
                (c).tv_usec += 1000000;             \
7892
            }                                       \
7893
        } while (0)
7894
7895
    #define CmpTimes(a, b, cmp)                     \
7896
        (((a).tv_sec  ==  (b).tv_sec) ?             \
7897
            ((a).tv_usec cmp (b).tv_usec) :         \
7898
            ((a).tv_sec  cmp (b).tv_sec))           \
7899
7900
7901
    /* do nothing handler */
7902
    static void myHandler(int signo)
7903
    {
7904
        (void)signo;
7905
        return;
7906
    }
7907
7908
7909
    static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
7910
                                 TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
7911
    {
7912
        int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
7913
        int       oldTimerOn = 0;   /* was timer already on */
7914
        WOLFSSL_TIMEVAL startTime;
7915
        WOLFSSL_TIMEVAL endTime;
7916
        WOLFSSL_TIMEVAL totalTime;
7917
        Itimerval myTimeout;
7918
        Itimerval oldTimeout; /* if old timer adjust from total time to reset */
7919
        struct sigaction act, oact;
7920
7921
        #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; }
7922
7923
        if (hsCb) {
7924
            ssl->hsInfoOn = 1;
7925
            InitHandShakeInfo(&ssl->handShakeInfo, ssl);
7926
        }
7927
        if (toCb) {
7928
            ssl->toInfoOn = 1;
7929
            InitTimeoutInfo(&ssl->timeoutInfo);
7930
7931
            if (gettimeofday(&startTime, 0) < 0)
7932
                ERR_OUT(GETTIME_ERROR);
7933
7934
            /* use setitimer to simulate getitimer, init 0 myTimeout */
7935
            myTimeout.it_interval.tv_sec  = 0;
7936
            myTimeout.it_interval.tv_usec = 0;
7937
            myTimeout.it_value.tv_sec     = 0;
7938
            myTimeout.it_value.tv_usec    = 0;
7939
            if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0)
7940
                ERR_OUT(SETITIMER_ERROR);
7941
7942
            if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) {
7943
                oldTimerOn = 1;
7944
7945
                /* is old timer going to expire before ours */
7946
                if (CmpTimes(oldTimeout.it_value, timeout, <)) {
7947
                    timeout.tv_sec  = oldTimeout.it_value.tv_sec;
7948
                    timeout.tv_usec = oldTimeout.it_value.tv_usec;
7949
                }
7950
            }
7951
            myTimeout.it_value.tv_sec  = timeout.tv_sec;
7952
            myTimeout.it_value.tv_usec = timeout.tv_usec;
7953
7954
            /* set up signal handler, don't restart socket send/recv */
7955
            act.sa_handler = myHandler;
7956
            sigemptyset(&act.sa_mask);
7957
            act.sa_flags = 0;
7958
#ifdef SA_INTERRUPT
7959
            act.sa_flags |= SA_INTERRUPT;
7960
#endif
7961
            if (sigaction(SIGALRM, &act, &oact) < 0)
7962
                ERR_OUT(SIGACT_ERROR);
7963
7964
            if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0)
7965
                ERR_OUT(SETITIMER_ERROR);
7966
        }
7967
7968
        /* do main work */
7969
#ifndef NO_WOLFSSL_CLIENT
7970
        if (ssl->options.side == WOLFSSL_CLIENT_END)
7971
            ret = wolfSSL_connect(ssl);
7972
#endif
7973
#ifndef NO_WOLFSSL_SERVER
7974
        if (ssl->options.side == WOLFSSL_SERVER_END)
7975
            ret = wolfSSL_accept(ssl);
7976
#endif
7977
7978
        /* do callbacks */
7979
        if (toCb) {
7980
            if (oldTimerOn) {
7981
                if (gettimeofday(&endTime, 0) < 0)
7982
                    ERR_OUT(SYSLIB_FAILED_E);
7983
                SubtractTimes(endTime, startTime, totalTime);
7984
                /* adjust old timer for elapsed time */
7985
                if (CmpTimes(totalTime, oldTimeout.it_value, <))
7986
                    SubtractTimes(oldTimeout.it_value, totalTime,
7987
                                  oldTimeout.it_value);
7988
                else {
7989
                    /* reset value to interval, may be off */
7990
                    oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec;
7991
                    oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec;
7992
                }
7993
                /* keep iter the same whether there or not */
7994
            }
7995
            /* restore old handler */
7996
            if (sigaction(SIGALRM, &oact, 0) < 0)
7997
                ret = SIGACT_ERROR;    /* more pressing error, stomp */
7998
            else
7999
                /* use old settings which may turn off (expired or not there) */
8000
                if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0)
8001
                    ret = SETITIMER_ERROR;
8002
8003
            /* if we had a timeout call callback */
8004
            if (ssl->timeoutInfo.timeoutName[0]) {
8005
                ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
8006
                ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
8007
                (toCb)(&ssl->timeoutInfo);
8008
            }
8009
            ssl->toInfoOn = 0;
8010
        }
8011
8012
        /* clean up buffers allocated by AddPacketInfo */
8013
        FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
8014
8015
        if (hsCb) {
8016
            FinishHandShakeInfo(&ssl->handShakeInfo);
8017
            (hsCb)(&ssl->handShakeInfo);
8018
            ssl->hsInfoOn = 0;
8019
        }
8020
        return ret;
8021
    }
8022
8023
8024
#ifndef NO_WOLFSSL_CLIENT
8025
8026
    int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
8027
                          TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
8028
    {
8029
        WOLFSSL_ENTER("wolfSSL_connect_ex");
8030
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
8031
    }
8032
8033
#endif
8034
8035
8036
#ifndef NO_WOLFSSL_SERVER
8037
8038
    int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
8039
                         TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
8040
    {
8041
        WOLFSSL_ENTER("wolfSSL_accept_ex");
8042
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
8043
    }
8044
8045
#endif
8046
8047
#endif /* WOLFSSL_CALLBACKS */
8048
8049
8050
#ifndef NO_PSK
8051
8052
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
8053
                                         wc_psk_client_callback cb)
8054
    {
8055
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
8056
8057
        if (ctx == NULL)
8058
            return;
8059
8060
        ctx->havePSK = 1;
8061
        ctx->client_psk_cb = cb;
8062
    }
8063
8064
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
8065
    {
8066
        byte haveRSA = 1;
8067
        int  keySz   = 0;
8068
8069
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
8070
8071
        if (ssl == NULL)
8072
            return;
8073
8074
        ssl->options.havePSK = 1;
8075
        ssl->options.client_psk_cb = cb;
8076
8077
        #ifdef NO_RSA
8078
            haveRSA = 0;
8079
        #endif
8080
        #ifndef NO_CERTS
8081
            keySz = ssl->buffers.keySz;
8082
        #endif
8083
        if (AllocateSuites(ssl) != 0)
8084
            return;
8085
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
8086
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
8087
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
8088
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
8089
    }
8090
    #ifdef OPENSSL_EXTRA
8091
    /**
8092
     * set call back function for psk session use
8093
     * @param ssl  a pointer to WOLFSSL structure
8094
     * @param cb   a function pointer to wc_psk_use_session_cb
8095
     * @return none
8096
     */
8097
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
8098
                                                wc_psk_use_session_cb_func cb)
8099
    {
8100
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
8101
8102
        if (ssl != NULL) {
8103
            ssl->options.havePSK = 1;
8104
            ssl->options.session_psk_cb = cb;
8105
        }
8106
8107
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
8108
    }
8109
    #endif
8110
8111
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
8112
                                         wc_psk_server_callback cb)
8113
    {
8114
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
8115
        if (ctx == NULL)
8116
            return;
8117
        ctx->havePSK = 1;
8118
        ctx->server_psk_cb = cb;
8119
    }
8120
8121
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
8122
    {
8123
        byte haveRSA = 1;
8124
        int  keySz   = 0;
8125
8126
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
8127
        if (ssl == NULL)
8128
            return;
8129
8130
        ssl->options.havePSK = 1;
8131
        ssl->options.server_psk_cb = cb;
8132
8133
        #ifdef NO_RSA
8134
            haveRSA = 0;
8135
        #endif
8136
        #ifndef NO_CERTS
8137
            keySz = ssl->buffers.keySz;
8138
        #endif
8139
        if (AllocateSuites(ssl) != 0)
8140
            return;
8141
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
8142
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
8143
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
8144
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
8145
    }
8146
8147
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
8148
    {
8149
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
8150
8151
        if (ssl == NULL || ssl->arrays == NULL)
8152
            return NULL;
8153
8154
        return ssl->arrays->server_hint;
8155
    }
8156
8157
8158
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
8159
    {
8160
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
8161
8162
        if (ssl == NULL || ssl->arrays == NULL)
8163
            return NULL;
8164
8165
        return ssl->arrays->client_identity;
8166
    }
8167
8168
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
8169
    {
8170
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
8171
        if (hint == 0)
8172
            ctx->server_hint[0] = '\0';
8173
        else {
8174
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
8175
            #ifdef WOLFSSL_QT
8176
            ctx->havePSK=1;
8177
            #endif
8178
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
8179
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
8180
        }
8181
        return WOLFSSL_SUCCESS;
8182
    }
8183
8184
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
8185
    {
8186
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
8187
8188
        if (ssl == NULL || ssl->arrays == NULL)
8189
            return WOLFSSL_FAILURE;
8190
8191
        if (hint == 0)
8192
            ssl->arrays->server_hint[0] = 0;
8193
        else {
8194
            XSTRNCPY(ssl->arrays->server_hint, hint,
8195
                                            sizeof(ssl->arrays->server_hint)-1);
8196
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
8197
        }
8198
        return WOLFSSL_SUCCESS;
8199
    }
8200
8201
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
8202
    {
8203
        return ssl ? ssl->options.psk_ctx : NULL;
8204
    }
8205
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
8206
    {
8207
        return ctx ? ctx->psk_ctx : NULL;
8208
    }
8209
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
8210
    {
8211
        if (ssl == NULL)
8212
            return WOLFSSL_FAILURE;
8213
        ssl->options.psk_ctx = psk_ctx;
8214
        return WOLFSSL_SUCCESS;
8215
    }
8216
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
8217
    {
8218
        if (ctx == NULL)
8219
            return WOLFSSL_FAILURE;
8220
        ctx->psk_ctx = psk_ctx;
8221
        return WOLFSSL_SUCCESS;
8222
    }
8223
#endif /* NO_PSK */
8224
8225
8226
#ifdef HAVE_ANON
8227
8228
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
8229
    {
8230
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
8231
8232
        if (ctx == NULL)
8233
            return WOLFSSL_FAILURE;
8234
8235
        ctx->useAnon = 1;
8236
8237
        return WOLFSSL_SUCCESS;
8238
    }
8239
8240
#endif /* HAVE_ANON */
8241
8242
#ifdef OPENSSL_EXTRA
8243
8244
    int wolfSSL_add_all_algorithms(void)
8245
    {
8246
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
8247
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
8248
            return WOLFSSL_SUCCESS;
8249
        else
8250
            return WOLFSSL_FATAL_ERROR;
8251
    }
8252
8253
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
8254
    {
8255
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
8256
8257
        if  (wolfSSL_add_all_algorithms() ==
8258
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
8259
        {
8260
            return WOLFSSL_FATAL_ERROR;
8261
        }
8262
8263
        return  WOLFSSL_SUCCESS;
8264
    }
8265
8266
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
8267
    {
8268
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
8269
        /* This function is currently the same as
8270
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
8271
        the use of a wolfssl.cnf type configuration file and is only used for
8272
        OpenSSL compatibility. */
8273
8274
        if (wolfSSL_add_all_algorithms() ==
8275
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
8276
        {
8277
            return WOLFSSL_FATAL_ERROR;
8278
        }
8279
        return WOLFSSL_SUCCESS;
8280
    }
8281
8282
#endif
8283
8284
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
8285
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8286
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
8287
    {
8288
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
8289
        if (mode)
8290
            ctx->quietShutdown = 1;
8291
    }
8292
8293
8294
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
8295
    {
8296
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
8297
        if (mode)
8298
            ssl->options.quietShutdown = 1;
8299
    }
8300
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
8301
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
8302
8303
#ifdef OPENSSL_EXTRA
8304
#ifndef NO_BIO
8305
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
8306
    {
8307
        WOLFSSL_ENTER("wolfSSL_set_bio");
8308
8309
        if (ssl == NULL) {
8310
            WOLFSSL_MSG("Bad argument, ssl was NULL");
8311
            return;
8312
        }
8313
8314
        /* free any existing WOLFSSL_BIOs in use but don't free those in
8315
         * a chain */
8316
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
8317
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
8318
                if (ssl->biowr != NULL && ssl->biowr->prev != NULL)
8319
                    wolfSSL_BIO_free(ssl->biowr);
8320
                ssl->biowr = NULL;
8321
            }
8322
            if (ssl->biord->prev != NULL)
8323
                wolfSSL_BIO_free(ssl->biord);
8324
            ssl->biord = NULL;
8325
        }
8326
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
8327
            if (ssl->biowr->prev != NULL)
8328
                wolfSSL_BIO_free(ssl->biowr);
8329
            ssl->biowr = NULL;
8330
        }
8331
8332
        /* set flag obviously */
8333
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
8334
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
8335
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
8336
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
8337
8338
        if (flags & WOLFSSL_BIO_FLAG_READ)
8339
            ssl->biord = rd;
8340
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
8341
            ssl->biowr = wr;
8342
8343
        /* set SSL to use BIO callbacks instead */
8344
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
8345
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
8346
        {
8347
            ssl->CBIORecv = SslBioReceive;
8348
        }
8349
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
8350
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
8351
        {
8352
            ssl->CBIOSend = SslBioSend;
8353
        }
8354
8355
        /* User programs should always retry reading from these BIOs */
8356
        if (rd) {
8357
            /* User writes to rd */
8358
            wolfSSL_BIO_set_retry_write(rd);
8359
        }
8360
        if (wr) {
8361
            /* User reads from wr */
8362
            wolfSSL_BIO_set_retry_read(wr);
8363
        }
8364
    }
8365
8366
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
8367
    {
8368
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
8369
    }
8370
8371
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
8372
    {
8373
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
8374
    }
8375
8376
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
8377
    {
8378
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
8379
    }
8380
8381
#endif /* !NO_BIO */
8382
#endif /* OPENSSL_EXTRA */
8383
8384
#ifdef WOLFSSL_CERT_SETUP_CB
8385
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8386
    /* registers client cert callback, called during handshake if server
8387
       requests client auth but user has not loaded client cert/key */
8388
    void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb)
8389
    {
8390
        WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb");
8391
8392
        if (ctx != NULL) {
8393
            ctx->CBClientCert = cb;
8394
        }
8395
    }
8396
#endif
8397
8398
    void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx,
8399
        CertSetupCallback cb, void *arg)
8400
    {
8401
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb");
8402
        if (ctx == NULL)
8403
            return;
8404
8405
        ctx->certSetupCb = cb;
8406
        ctx->certSetupCbArg = arg;
8407
    }
8408
8409
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
8410
            const byte** suites, word16* suiteSz,
8411
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
8412
    {
8413
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
8414
8415
        if (suites != NULL)
8416
            *suites = NULL;
8417
        if (suiteSz != NULL)
8418
            *suiteSz = 0;
8419
        if (hashSigAlgo != NULL)
8420
            *hashSigAlgo = NULL;
8421
        if (hashSigAlgoSz != NULL)
8422
            *hashSigAlgoSz = 0;
8423
8424
        if (ssl != NULL && ssl->clSuites != NULL) {
8425
            if (suites != NULL && suiteSz != NULL) {
8426
                *suites = ssl->clSuites->suites;
8427
                *suiteSz = ssl->clSuites->suiteSz;
8428
            }
8429
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
8430
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
8431
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
8432
            }
8433
            return WOLFSSL_SUCCESS;
8434
        }
8435
        return WOLFSSL_FAILURE;
8436
    }
8437
8438
#ifndef NO_TLS
8439
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
8440
            byte second)
8441
    {
8442
        WOLFSSL_CIPHERSUITE_INFO info;
8443
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
8444
                CipherRequires(first, second, REQUIRES_RSA_SIG));
8445
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
8446
                /* Static ECC ciphers may require RSA for authentication */
8447
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
8448
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
8449
        info.eccStatic =
8450
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
8451
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
8452
        return info;
8453
    }
8454
#endif
8455
8456
    /**
8457
     * @param first First byte of the hash and signature algorithm
8458
     * @param second Second byte of the hash and signature algorithm
8459
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
8460
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
8461
     */
8462
    int wolfSSL_get_sigalg_info(byte first, byte second,
8463
            int* hashAlgo, int* sigAlgo)
8464
    {
8465
        byte input[2];
8466
        byte hashType;
8467
        byte sigType;
8468
8469
        if (hashAlgo == NULL || sigAlgo == NULL)
8470
            return BAD_FUNC_ARG;
8471
8472
        input[0] = first;
8473
        input[1] = second;
8474
        DecodeSigAlg(input, &hashType, &sigType);
8475
8476
        /* cast so that compiler reminds us of unimplemented values */
8477
        switch ((enum SignatureAlgorithm)sigType) {
8478
        case anonymous_sa_algo:
8479
            *sigAlgo = ANONk;
8480
            break;
8481
        case rsa_sa_algo:
8482
            *sigAlgo = RSAk;
8483
            break;
8484
        case dsa_sa_algo:
8485
            *sigAlgo = DSAk;
8486
            break;
8487
        case ecc_dsa_sa_algo:
8488
        case ecc_brainpool_sa_algo:
8489
            *sigAlgo = ECDSAk;
8490
            break;
8491
        case rsa_pss_sa_algo:
8492
            *sigAlgo = RSAPSSk;
8493
            break;
8494
        case ed25519_sa_algo:
8495
            *sigAlgo = ED25519k;
8496
            break;
8497
        case rsa_pss_pss_algo:
8498
            *sigAlgo = RSAPSSk;
8499
            break;
8500
        case ed448_sa_algo:
8501
            *sigAlgo = ED448k;
8502
            break;
8503
        case falcon_level1_sa_algo:
8504
            *sigAlgo = FALCON_LEVEL1k;
8505
            break;
8506
        case falcon_level5_sa_algo:
8507
            *sigAlgo = FALCON_LEVEL5k;
8508
            break;
8509
        case dilithium_level2_sa_algo:
8510
            *sigAlgo = ML_DSA_LEVEL2k;
8511
            break;
8512
        case dilithium_level3_sa_algo:
8513
            *sigAlgo = ML_DSA_LEVEL3k;
8514
            break;
8515
        case dilithium_level5_sa_algo:
8516
            *sigAlgo = ML_DSA_LEVEL5k;
8517
            break;
8518
        case sm2_sa_algo:
8519
            *sigAlgo = SM2k;
8520
            break;
8521
        case invalid_sa_algo:
8522
        case any_sa_algo:
8523
        default:
8524
            *hashAlgo = WC_HASH_TYPE_NONE;
8525
            *sigAlgo = 0;
8526
            return BAD_FUNC_ARG;
8527
        }
8528
8529
        /* cast so that compiler reminds us of unimplemented values */
8530
        switch((enum wc_MACAlgorithm)hashType) {
8531
        case no_mac:
8532
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
8533
            *hashAlgo = WC_HASH_TYPE_NONE;
8534
            break;
8535
        case md5_mac:
8536
            *hashAlgo = WC_HASH_TYPE_MD5;
8537
            break;
8538
        case sha_mac:
8539
            *hashAlgo = WC_HASH_TYPE_SHA;
8540
            break;
8541
        case sha224_mac:
8542
            *hashAlgo = WC_HASH_TYPE_SHA224;
8543
            break;
8544
        case sha256_mac:
8545
            *hashAlgo = WC_HASH_TYPE_SHA256;
8546
            break;
8547
        case sha384_mac:
8548
            *hashAlgo = WC_HASH_TYPE_SHA384;
8549
            break;
8550
        case sha512_mac:
8551
            *hashAlgo = WC_HASH_TYPE_SHA512;
8552
            break;
8553
        case blake2b_mac:
8554
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
8555
            break;
8556
        case sm3_mac:
8557
#ifdef WOLFSSL_SM3
8558
            *hashAlgo = WC_HASH_TYPE_SM3;
8559
#else
8560
            *hashAlgo = WC_HASH_TYPE_NONE;
8561
#endif
8562
            break;
8563
        default:
8564
            *hashAlgo = WC_HASH_TYPE_NONE;
8565
            *sigAlgo = 0;
8566
            return BAD_FUNC_ARG;
8567
        }
8568
        return 0;
8569
    }
8570
8571
    /**
8572
     * Internal wrapper for calling certSetupCb
8573
     * @param ssl The SSL/TLS Object
8574
     * @return 0 on success
8575
     */
8576
    int CertSetupCbWrapper(WOLFSSL* ssl)
8577
    {
8578
        int ret = 0;
8579
        if (ssl->ctx->certSetupCb != NULL) {
8580
            WOLFSSL_MSG("Calling user cert setup callback");
8581
            ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg);
8582
            if (ret == 1) {
8583
                WOLFSSL_MSG("User cert callback returned success");
8584
                ret = 0;
8585
            }
8586
            else if (ret == 0) {
8587
                SendAlert(ssl, alert_fatal, internal_error);
8588
                ret = CLIENT_CERT_CB_ERROR;
8589
            }
8590
            else if (ret < 0) {
8591
                ret = WOLFSSL_ERROR_WANT_X509_LOOKUP;
8592
            }
8593
            else {
8594
                WOLFSSL_MSG("Unexpected user callback return");
8595
                ret = CLIENT_CERT_CB_ERROR;
8596
            }
8597
        }
8598
        return ret;
8599
    }
8600
#endif /* WOLFSSL_CERT_SETUP_CB */
8601
8602
#ifdef OPENSSL_EXTRA
8603
8604
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
8605
        && !defined(WC_NO_RNG)
8606
    static const byte srp_N[] = {
8607
        0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8,
8608
        0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF,
8609
        0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6,
8610
        0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13,
8611
        0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B,
8612
        0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7,
8613
        0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69,
8614
        0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85,
8615
        0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC,
8616
        0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E,
8617
        0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F,
8618
        0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3
8619
    };
8620
    static const byte srp_g[] = {
8621
        0x02
8622
    };
8623
8624
    int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username)
8625
    {
8626
        int r = 0;
8627
        SrpSide srp_side = SRP_CLIENT_SIDE;
8628
8629
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username");
8630
        if (ctx == NULL || ctx->srp == NULL || username==NULL)
8631
            return WOLFSSL_FAILURE;
8632
8633
        if (ctx->method->side == WOLFSSL_SERVER_END){
8634
            srp_side = SRP_SERVER_SIDE;
8635
        } else if (ctx->method->side == WOLFSSL_CLIENT_END){
8636
            srp_side = SRP_CLIENT_SIDE;
8637
        } else {
8638
            WOLFSSL_MSG("Init CTX failed");
8639
            return WOLFSSL_FAILURE;
8640
        }
8641
8642
        if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) {
8643
            WOLFSSL_MSG("Init SRP CTX failed");
8644
            XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
8645
            ctx->srp = NULL;
8646
            return WOLFSSL_FAILURE;
8647
        }
8648
        r = wc_SrpSetUsername(ctx->srp, (const byte*)username,
8649
                              (word32)XSTRLEN(username));
8650
        if (r < 0) {
8651
            WOLFSSL_MSG("fail to set srp username.");
8652
            return WOLFSSL_FAILURE;
8653
        }
8654
8655
        /* if wolfSSL_CTX_set_srp_password has already been called, */
8656
        /* use saved password here */
8657
        if (ctx->srp_password != NULL) {
8658
            if (ctx->srp->user == NULL)
8659
                return WOLFSSL_FAILURE;
8660
            return wolfSSL_CTX_set_srp_password(ctx, (char*)ctx->srp_password);
8661
        }
8662
8663
        return WOLFSSL_SUCCESS;
8664
    }
8665
8666
    int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password)
8667
    {
8668
        int r;
8669
        byte salt[SRP_SALT_SIZE];
8670
8671
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password");
8672
        if (ctx == NULL || ctx->srp == NULL || password == NULL)
8673
            return WOLFSSL_FAILURE;
8674
8675
        if (ctx->srp->user != NULL) {
8676
            WC_RNG rng;
8677
            if (wc_InitRng(&rng) < 0) {
8678
                WOLFSSL_MSG("wc_InitRng failed");
8679
                return WOLFSSL_FAILURE;
8680
            }
8681
            XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
8682
            r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
8683
            wc_FreeRng(&rng);
8684
            if (r <  0) {
8685
                WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
8686
                return WOLFSSL_FAILURE;
8687
            }
8688
            if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
8689
                                srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
8690
                                salt, sizeof(salt)/sizeof(salt[0])) < 0){
8691
                WOLFSSL_MSG("wc_SrpSetParam failed");
8692
                return WOLFSSL_FAILURE;
8693
            }
8694
            r = wc_SrpSetPassword(ctx->srp, (const byte*)password,
8695
                                  (word32)XSTRLEN(password));
8696
            if (r < 0) {
8697
                WOLFSSL_MSG("wc_SrpSetPassword failed.");
8698
                return WOLFSSL_FAILURE;
8699
            }
8700
            XFREE(ctx->srp_password, NULL, DYNAMIC_TYPE_SRP);
8701
            ctx->srp_password = NULL;
8702
        } else {
8703
            /* save password for wolfSSL_set_srp_username */
8704
            XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
8705
8706
            ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap,
8707
                                               DYNAMIC_TYPE_SRP);
8708
            if (ctx->srp_password == NULL){
8709
                WOLFSSL_MSG("memory allocation error");
8710
                return WOLFSSL_FAILURE;
8711
            }
8712
            XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1);
8713
        }
8714
        return WOLFSSL_SUCCESS;
8715
    }
8716
8717
    /**
8718
     * The modulus passed to wc_SrpSetParams in ssl.c is constant so check
8719
     * that the requested strength is less than or equal to the size of the
8720
     * static modulus size.
8721
     * @param ctx Not used
8722
     * @param strength Minimum number of bits for the modulus
8723
     * @return 1 if strength is less than or equal to static modulus
8724
     *         0 if strength is greater than static modulus
8725
     */
8726
    int  wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength)
8727
    {
8728
        (void)ctx;
8729
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength");
8730
        if (strength > (int)(sizeof(srp_N)*8)) {
8731
            WOLFSSL_MSG("Bad Parameter");
8732
            return WOLFSSL_FAILURE;
8733
        }
8734
        return WOLFSSL_SUCCESS;
8735
    }
8736
8737
    char* wolfSSL_get_srp_username(WOLFSSL *ssl)
8738
    {
8739
        if (ssl && ssl->ctx && ssl->ctx->srp) {
8740
            return (char*) ssl->ctx->srp->user;
8741
        }
8742
        return NULL;
8743
    }
8744
    #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */
8745
8746
    /* keyblock size in bytes or -1 */
8747
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
8748
    {
8749
        if (ssl == NULL)
8750
            return WOLFSSL_FATAL_ERROR;
8751
8752
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
8753
                    ssl->specs.hash_size);
8754
    }
8755
8756
#endif /* OPENSSL_EXTRA */
8757
8758
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
8759
    defined(WOLFSSL_WPAS_SMALL)
8760
8761
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
8762
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
8763
                                     unsigned char** sr, unsigned int* srLen,
8764
                                     unsigned char** cr, unsigned int* crLen)
8765
    {
8766
        if (ssl == NULL || ssl->arrays == NULL)
8767
            return WOLFSSL_FATAL_ERROR;
8768
8769
        *ms = ssl->arrays->masterSecret;
8770
        *sr = ssl->arrays->serverRandom;
8771
        *cr = ssl->arrays->clientRandom;
8772
8773
        *msLen = SECRET_LEN;
8774
        *srLen = RAN_LEN;
8775
        *crLen = RAN_LEN;
8776
8777
        return WOLFSSL_SUCCESS;
8778
    }
8779
8780
    void wolfSSL_set_accept_state(WOLFSSL* ssl)
8781
    {
8782
        WOLFSSL_ENTER("wolfSSL_set_accept_state");
8783
8784
        if (ssl == NULL)
8785
            return;
8786
8787
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
8788
    #ifdef HAVE_ECC
8789
            WC_DECLARE_VAR(key, ecc_key, 1, 0);
8790
            word32 idx = 0;
8791
8792
        #ifdef WOLFSSL_SMALL_STACK
8793
            key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
8794
                                    DYNAMIC_TYPE_ECC);
8795
            if (key == NULL) {
8796
                WOLFSSL_MSG("Error allocating memory for ecc_key");
8797
            }
8798
        #endif
8799
            if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) {
8800
                if (wc_ecc_init(key) >= 0) {
8801
                    if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
8802
                            key, ssl->buffers.key->length) != 0) {
8803
                        ssl->options.haveECDSAsig = 0;
8804
                        ssl->options.haveECC = 0;
8805
                        ssl->options.haveStaticECC = 0;
8806
                    }
8807
                    wc_ecc_free(key);
8808
                }
8809
            }
8810
            WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
8811
    #endif
8812
8813
    #ifndef NO_DH
8814
            if (!ssl->options.haveDH && ssl->ctx->haveDH) {
8815
                ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
8816
                ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
8817
                ssl->options.haveDH = 1;
8818
            }
8819
    #endif
8820
        }
8821
8822
        if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
8823
            WOLFSSL_MSG("Error initializing server side");
8824
        }
8825
    }
8826
8827
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
8828
8829
    /* return true if connection established */
8830
    /* this works for TLS and DTLS */
8831
    int wolfSSL_is_init_finished(const WOLFSSL* ssl)
8832
0
    {
8833
0
        if (ssl == NULL)
8834
0
            return 0;
8835
8836
#if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
8837
        if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls
8838
                && IsAtLeastTLSv1_3(ssl->version)) {
8839
            return ssl->options.serverState == SERVER_FINISHED_ACKED;
8840
        }
8841
#endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT */
8842
8843
        /* Can't use ssl->options.connectState and ssl->options.acceptState
8844
         * because they differ in meaning for TLS <=1.2 and 1.3 */
8845
0
        if (ssl->options.handShakeState == HANDSHAKE_DONE)
8846
0
            return 1;
8847
8848
0
        return 0;
8849
0
    }
8850
8851
#ifdef OPENSSL_EXTRA
8852
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
8853
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
8854
    {
8855
        /* wolfSSL verifies all these internally */
8856
        (void)ctx;
8857
        (void)f;
8858
    }
8859
8860
8861
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
8862
    {
8863
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
8864
        if(ssl==NULL) {
8865
            WOLFSSL_MSG("Shutdown not set. ssl is null");
8866
            return;
8867
        }
8868
8869
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
8870
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
8871
    }
8872
#endif
8873
8874
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
8875
0
    {
8876
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
8877
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
8878
0
        if(ctx == NULL)
8879
0
            return BAD_FUNC_ARG;
8880
0
        return (long)ctx->mask;
8881
0
    }
8882
8883
    /* forward declaration */
8884
    static long wolf_set_options(long old_op, long op);
8885
8886
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
8887
0
    {
8888
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
8889
8890
0
        if (ctx == NULL)
8891
0
            return BAD_FUNC_ARG;
8892
8893
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
8894
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
8895
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
8896
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
8897
          ctx->noTicketTls12 = 1;
8898
        }
8899
        /* This code is here for documentation purpose. You must not turn off
8900
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
8901
         * Because we need to support both stateful and stateless tickets.
8902
        #ifdef WOLFSSL_TLS13
8903
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
8904
                ctx->noTicketTls13 = 1;
8905
            }
8906
        #endif
8907
        */
8908
#endif
8909
0
        return (long)ctx->mask;
8910
0
    }
8911
8912
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
8913
0
    {
8914
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
8915
0
        if(ctx == NULL)
8916
0
            return BAD_FUNC_ARG;
8917
0
        ctx->mask &= (unsigned long)~opt;
8918
0
        return (long)ctx->mask;
8919
0
    }
8920
8921
#ifdef OPENSSL_EXTRA
8922
8923
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
8924
    {
8925
        WOLFSSL_ENTER("wolfSSL_set_rfd");
8926
        ssl->rfd = rfd;      /* not used directly to allow IO callbacks */
8927
8928
        ssl->IOCB_ReadCtx  = &ssl->rfd;
8929
8930
    #ifdef WOLFSSL_DTLS
8931
        if (ssl->options.dtls) {
8932
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
8933
            ssl->buffers.dtlsCtx.rfd = rfd;
8934
        }
8935
    #endif
8936
8937
        return WOLFSSL_SUCCESS;
8938
    }
8939
8940
8941
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
8942
    {
8943
        WOLFSSL_ENTER("wolfSSL_set_wfd");
8944
        ssl->wfd = wfd;      /* not used directly to allow IO callbacks */
8945
8946
        ssl->IOCB_WriteCtx  = &ssl->wfd;
8947
8948
        return WOLFSSL_SUCCESS;
8949
    }
8950
#endif /* OPENSSL_EXTRA */
8951
8952
#ifdef WOLFSSL_ENCRYPTED_KEYS
8953
8954
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
8955
                                                   void* userdata)
8956
    {
8957
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
8958
        if (ctx)
8959
            ctx->passwd_userdata = userdata;
8960
    }
8961
8962
8963
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
8964
                                           cb)
8965
    {
8966
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
8967
        if (ctx)
8968
            ctx->passwd_cb = cb;
8969
    }
8970
8971
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
8972
    {
8973
        if (ctx == NULL || ctx->passwd_cb == NULL) {
8974
            return NULL;
8975
        }
8976
8977
        return ctx->passwd_cb;
8978
    }
8979
8980
8981
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
8982
    {
8983
        if (ctx == NULL) {
8984
            return NULL;
8985
        }
8986
8987
        return ctx->passwd_userdata;
8988
    }
8989
8990
#endif /* WOLFSSL_ENCRYPTED_KEYS */
8991
8992
8993
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
8994
    unsigned long wolfSSL_ERR_get_error(void)
8995
    {
8996
        WOLFSSL_ENTER("wolfSSL_ERR_get_error");
8997
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
8998
        return (unsigned long)wc_GetErrorNodeErr();
8999
#else
9000
        return (unsigned long)(0 - NOT_COMPILED_IN);
9001
#endif
9002
    }
9003
#endif
9004
9005
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
9006
9007
    int wolfSSL_num_locks(void)
9008
    {
9009
        return 0;
9010
    }
9011
9012
    void wolfSSL_set_locking_callback(mutex_cb* f)
9013
    {
9014
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
9015
9016
        if (wc_SetMutexCb(f) != 0) {
9017
            WOLFSSL_MSG("Error when setting mutex call back");
9018
        }
9019
    }
9020
9021
    mutex_cb* wolfSSL_get_locking_callback(void)
9022
    {
9023
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
9024
9025
        return wc_GetMutexCb();
9026
    }
9027
9028
9029
    typedef unsigned long (idCb)(void);
9030
    static idCb* inner_idCb = NULL;
9031
9032
    unsigned long wolfSSL_thread_id(void)
9033
    {
9034
        if (inner_idCb != NULL) {
9035
            return inner_idCb();
9036
        }
9037
        else {
9038
            return 0;
9039
        }
9040
    }
9041
9042
9043
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
9044
    {
9045
        inner_idCb = f;
9046
    }
9047
9048
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
9049
#ifndef NO_BIO
9050
    /* print out and clear all errors */
9051
    void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio)
9052
    {
9053
        const char* file = NULL;
9054
        const char* reason = NULL;
9055
        int ret;
9056
        int line = 0;
9057
        char buf[WOLFSSL_MAX_ERROR_SZ * 2];
9058
9059
        WOLFSSL_ENTER("wolfSSL_ERR_print_errors");
9060
9061
        if (bio == NULL) {
9062
            WOLFSSL_MSG("BIO passed in was null");
9063
            return;
9064
        }
9065
9066
        do {
9067
        ret = wc_PeekErrorNode(0, &file, &reason, &line);
9068
        if (ret >= 0) {
9069
            const char* r = wolfSSL_ERR_reason_error_string(
9070
                (unsigned long)(0 - ret));
9071
            if (XSNPRINTF(buf, sizeof(buf),
9072
                          "error:%d:wolfSSL library:%s:%s:%d\n",
9073
                          ret, r, file, line)
9074
                >= (int)sizeof(buf))
9075
            {
9076
                WOLFSSL_MSG("Buffer overrun formatting error message");
9077
            }
9078
            wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf));
9079
            wc_RemoveErrorNode(0);
9080
        }
9081
        } while (ret >= 0);
9082
        if (wolfSSL_BIO_write(bio, "", 1) != 1) {
9083
            WOLFSSL_MSG("Issue writing final string terminator");
9084
        }
9085
    }
9086
#endif /* !NO_BIO */
9087
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
9088
9089
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
9090
9091
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
9092
    defined(HAVE_SECRET_CALLBACK)
9093
#if !defined(NO_WOLFSSL_SERVER)
9094
/* Return the amount of random bytes copied over or error case.
9095
 * ssl : ssl struct after handshake
9096
 * out : buffer to hold random bytes
9097
 * outSz : either 0 (return max buffer sz) or size of out buffer
9098
 */
9099
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
9100
                                                                   size_t outSz)
9101
{
9102
    size_t size;
9103
9104
    /* return max size of buffer */
9105
    if (outSz == 0) {
9106
        return RAN_LEN;
9107
    }
9108
9109
    if (ssl == NULL || out == NULL) {
9110
        return 0;
9111
    }
9112
9113
    if (ssl->arrays == NULL) {
9114
        WOLFSSL_MSG("Arrays struct not saved after handshake");
9115
        return 0;
9116
    }
9117
9118
    if (outSz > RAN_LEN) {
9119
        size = RAN_LEN;
9120
    }
9121
    else {
9122
        size = outSz;
9123
    }
9124
9125
    XMEMCPY(out, ssl->arrays->serverRandom, size);
9126
    return size;
9127
}
9128
#endif /* !NO_WOLFSSL_SERVER */
9129
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
9130
9131
#ifdef OPENSSL_EXTRA
9132
#if !defined(NO_WOLFSSL_SERVER)
9133
/* Used to get the peer ephemeral public key sent during the connection
9134
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
9135
 *       before the ephemeral key is stored.
9136
 * return WOLFSSL_SUCCESS on success */
9137
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
9138
{
9139
    WOLFSSL_EVP_PKEY* ret = NULL;
9140
9141
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
9142
9143
    if (ssl == NULL || pkey == NULL) {
9144
        WOLFSSL_MSG("Bad argument passed in");
9145
        return WOLFSSL_FAILURE;
9146
    }
9147
9148
#ifdef HAVE_ECC
9149
    if (ssl->peerEccKey != NULL) {
9150
        unsigned char* der;
9151
        const unsigned char* pt;
9152
        unsigned int   derSz = 0;
9153
        int sz;
9154
9155
        PRIVATE_KEY_UNLOCK();
9156
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
9157
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
9158
        {
9159
            WOLFSSL_MSG("get ecc der size failed");
9160
            PRIVATE_KEY_LOCK();
9161
            return WOLFSSL_FAILURE;
9162
        }
9163
        PRIVATE_KEY_LOCK();
9164
9165
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
9166
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
9167
        if (der == NULL) {
9168
            WOLFSSL_MSG("Memory error");
9169
            return WOLFSSL_FAILURE;
9170
        }
9171
9172
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
9173
            WOLFSSL_MSG("get ecc der failed");
9174
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
9175
            return WOLFSSL_FAILURE;
9176
        }
9177
        pt = der; /* in case pointer gets advanced */
9178
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
9179
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
9180
    }
9181
#endif
9182
9183
    *pkey = ret;
9184
#ifdef HAVE_ECC
9185
    if (ret != NULL)
9186
        return WOLFSSL_SUCCESS;
9187
    else
9188
#endif
9189
        return WOLFSSL_FAILURE;
9190
}
9191
9192
#endif /* !NO_WOLFSSL_SERVER */
9193
9194
/**
9195
 * This function checks if any compiled in protocol versions are
9196
 * left enabled after calls to set_min or set_max API.
9197
 * @param major The SSL/TLS major version
9198
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
9199
 *         protocol versions are left enabled.
9200
 */
9201
static int CheckSslMethodVersion(byte major, unsigned long options)
9202
{
9203
    int sanityConfirmed = 0;
9204
9205
    (void)options;
9206
9207
    switch (major) {
9208
    #ifndef NO_TLS
9209
        case SSLv3_MAJOR:
9210
            #ifdef WOLFSSL_ALLOW_SSLV3
9211
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
9212
                    sanityConfirmed = 1;
9213
                }
9214
            #endif
9215
            #ifndef NO_OLD_TLS
9216
                if (!(options & WOLFSSL_OP_NO_TLSv1))
9217
                    sanityConfirmed = 1;
9218
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
9219
                    sanityConfirmed = 1;
9220
            #endif
9221
            #ifndef WOLFSSL_NO_TLS12
9222
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
9223
                    sanityConfirmed = 1;
9224
            #endif
9225
            #ifdef WOLFSSL_TLS13
9226
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
9227
                    sanityConfirmed = 1;
9228
            #endif
9229
            break;
9230
    #endif
9231
    #ifdef WOLFSSL_DTLS
9232
        case DTLS_MAJOR:
9233
            sanityConfirmed = 1;
9234
            break;
9235
    #endif
9236
        default:
9237
            WOLFSSL_MSG("Invalid major version");
9238
            return WOLFSSL_FAILURE;
9239
    }
9240
    if (!sanityConfirmed) {
9241
        WOLFSSL_MSG("All compiled in TLS versions disabled");
9242
        return WOLFSSL_FAILURE;
9243
    }
9244
    return WOLFSSL_SUCCESS;
9245
}
9246
9247
/**
9248
 * protoVerTbl holds (D)TLS version numbers in ascending order.
9249
 * Except DTLS versions, the newer version is located in the latter part of
9250
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
9251
 * wolfSSL_CTX_set_max_proto_version.
9252
 */
9253
static const int protoVerTbl[] = {
9254
    SSL3_VERSION,
9255
    TLS1_VERSION,
9256
    TLS1_1_VERSION,
9257
    TLS1_2_VERSION,
9258
    TLS1_3_VERSION,
9259
    DTLS1_VERSION,
9260
    DTLS1_2_VERSION
9261
};
9262
/* number of protocol versions listed in protoVerTbl */
9263
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
9264
9265
/**
9266
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
9267
 * version to use by SSL objects created from this WOLFSSL_CTX.
9268
 * This API guarantees that a version of SSL/TLS lower than specified
9269
 * here will not be allowed. If the version specified is not compiled in
9270
 * then this API sets the lowest compiled in protocol version.
9271
 * This API also accept 0 as version, to set the minimum version automatically.
9272
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
9273
 * are enabled.
9274
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
9275
 * @param version Any of the following
9276
 *          * 0
9277
 *          * SSL3_VERSION
9278
 *          * TLS1_VERSION
9279
 *          * TLS1_1_VERSION
9280
 *          * TLS1_2_VERSION
9281
 *          * TLS1_3_VERSION
9282
 *          * DTLS1_VERSION
9283
 *          * DTLS1_2_VERSION
9284
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
9285
 *         protocol versions are left enabled.
9286
 */
9287
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
9288
{
9289
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
9290
9291
    if (ctx == NULL) {
9292
        return WOLFSSL_FAILURE;
9293
    }
9294
9295
    switch (version) {
9296
#ifndef NO_TLS
9297
        case SSL3_VERSION:
9298
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
9299
            ctx->minDowngrade = SSLv3_MINOR;
9300
            break;
9301
#endif
9302
        case TLS1_VERSION:
9303
        #ifdef WOLFSSL_ALLOW_TLSV10
9304
            ctx->minDowngrade = TLSv1_MINOR;
9305
            break;
9306
        #endif
9307
        case TLS1_1_VERSION:
9308
        #ifndef NO_OLD_TLS
9309
            ctx->minDowngrade = TLSv1_1_MINOR;
9310
            break;
9311
        #endif
9312
        case TLS1_2_VERSION:
9313
        #ifndef WOLFSSL_NO_TLS12
9314
            ctx->minDowngrade = TLSv1_2_MINOR;
9315
            break;
9316
        #endif
9317
        case TLS1_3_VERSION:
9318
        #ifdef WOLFSSL_TLS13
9319
            ctx->minDowngrade = TLSv1_3_MINOR;
9320
            break;
9321
        #endif
9322
#endif
9323
#ifdef WOLFSSL_DTLS
9324
        case DTLS1_VERSION:
9325
    #ifndef NO_OLD_TLS
9326
            ctx->minDowngrade = DTLS_MINOR;
9327
            break;
9328
    #endif
9329
        case DTLS1_2_VERSION:
9330
            ctx->minDowngrade = DTLSv1_2_MINOR;
9331
            break;
9332
#endif
9333
        default:
9334
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9335
            return WOLFSSL_FAILURE;
9336
    }
9337
9338
    switch (version) {
9339
#ifndef NO_TLS
9340
    case TLS1_3_VERSION:
9341
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
9342
        FALL_THROUGH;
9343
    case TLS1_2_VERSION:
9344
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
9345
        FALL_THROUGH;
9346
    case TLS1_1_VERSION:
9347
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
9348
        FALL_THROUGH;
9349
    case TLS1_VERSION:
9350
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
9351
        break;
9352
    case SSL3_VERSION:
9353
    case SSL2_VERSION:
9354
        /* Nothing to do here */
9355
        break;
9356
#endif
9357
#ifdef WOLFSSL_DTLS
9358
    case DTLS1_VERSION:
9359
    case DTLS1_2_VERSION:
9360
        break;
9361
#endif
9362
    default:
9363
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9364
        return WOLFSSL_FAILURE;
9365
    }
9366
9367
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
9368
}
9369
9370
/* Sets the min protocol version allowed with WOLFSSL_CTX
9371
 * returns WOLFSSL_SUCCESS on success */
9372
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
9373
{
9374
    int ret;
9375
    int proto    = 0;
9376
    int maxProto = 0;
9377
    int i;
9378
    int idx = 0;
9379
9380
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
9381
9382
    if (ctx == NULL) {
9383
        return WOLFSSL_FAILURE;
9384
    }
9385
9386
    if (version != 0) {
9387
        proto = version;
9388
        ctx->minProto = 0; /* turn min proto flag off */
9389
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
9390
            if (protoVerTbl[i] == version) {
9391
                break;
9392
            }
9393
        }
9394
    }
9395
    else {
9396
        /* when 0 is specified as version, try to find out the min version */
9397
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
9398
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
9399
            if (ret == WOLFSSL_SUCCESS) {
9400
                proto = protoVerTbl[i];
9401
                ctx->minProto = 1; /* turn min proto flag on */
9402
                break;
9403
            }
9404
        }
9405
    }
9406
9407
    /* check case where max > min , if so then clear the NO_* options
9408
     * i is the index into the table for proto version used, see if the max
9409
     * proto version index found is smaller */
9410
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
9411
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
9412
        if (protoVerTbl[idx] == maxProto) {
9413
            break;
9414
        }
9415
    }
9416
    if (idx < i) {
9417
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
9418
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
9419
                WOLFSSL_OP_NO_TLSv1_3);
9420
    }
9421
9422
    ret = Set_CTX_min_proto_version(ctx, proto);
9423
    return ret;
9424
}
9425
9426
/**
9427
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
9428
 * version to use by SSL objects created from this WOLFSSL_CTX.
9429
 * This API guarantees that a version of SSL/TLS higher than specified
9430
 * here will not be allowed. If the version specified is not compiled in
9431
 * then this API sets the highest compiled in protocol version.
9432
 * This API also accept 0 as version, to set the maximum version automatically.
9433
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
9434
 * are enabled.
9435
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
9436
 * @param ver Any of the following
9437
 *          * 0
9438
 *          * SSL3_VERSION
9439
 *          * TLS1_VERSION
9440
 *          * TLS1_1_VERSION
9441
 *          * TLS1_2_VERSION
9442
 *          * TLS1_3_VERSION
9443
 *          * DTLS1_VERSION
9444
 *          * DTLS1_2_VERSION
9445
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
9446
 *         protocol versions are left enabled.
9447
 */
9448
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
9449
{
9450
    int ret;
9451
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
9452
9453
    if (!ctx || !ctx->method) {
9454
        WOLFSSL_MSG("Bad parameter");
9455
        return WOLFSSL_FAILURE;
9456
    }
9457
9458
    switch (ver) {
9459
#ifndef NO_TLS
9460
#ifndef NO_OLD_TLS
9461
    case SSL2_VERSION:
9462
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
9463
        return WOLFSSL_FAILURE;
9464
#endif
9465
    case SSL3_VERSION:
9466
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
9467
        FALL_THROUGH;
9468
    case TLS1_VERSION:
9469
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
9470
        FALL_THROUGH;
9471
    case TLS1_1_VERSION:
9472
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
9473
        FALL_THROUGH;
9474
    case TLS1_2_VERSION:
9475
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
9476
        FALL_THROUGH;
9477
    case TLS1_3_VERSION:
9478
        /* Nothing to do here */
9479
        break;
9480
#endif
9481
#ifdef WOLFSSL_DTLS
9482
    case DTLS1_VERSION:
9483
    case DTLS1_2_VERSION:
9484
        break;
9485
#endif
9486
    default:
9487
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9488
        return WOLFSSL_FAILURE;
9489
    }
9490
9491
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
9492
    if (ret == WOLFSSL_SUCCESS) {
9493
        /* Check the major */
9494
        switch (ver) {
9495
    #ifndef NO_TLS
9496
        case SSL3_VERSION:
9497
        case TLS1_VERSION:
9498
        case TLS1_1_VERSION:
9499
        case TLS1_2_VERSION:
9500
        case TLS1_3_VERSION:
9501
            if (ctx->method->version.major != SSLv3_MAJOR) {
9502
                WOLFSSL_MSG("Mismatched protocol version");
9503
                return WOLFSSL_FAILURE;
9504
            }
9505
            break;
9506
    #endif
9507
    #ifdef WOLFSSL_DTLS
9508
        case DTLS1_VERSION:
9509
        case DTLS1_2_VERSION:
9510
            if (ctx->method->version.major != DTLS_MAJOR) {
9511
                WOLFSSL_MSG("Mismatched protocol version");
9512
                return WOLFSSL_FAILURE;
9513
            }
9514
            break;
9515
    #endif
9516
        }
9517
        /* Update the method */
9518
        switch (ver) {
9519
    #ifndef NO_TLS
9520
        case SSL3_VERSION:
9521
            ctx->method->version.minor = SSLv3_MINOR;
9522
            break;
9523
        case TLS1_VERSION:
9524
            ctx->method->version.minor = TLSv1_MINOR;
9525
            break;
9526
        case TLS1_1_VERSION:
9527
            ctx->method->version.minor = TLSv1_1_MINOR;
9528
            break;
9529
        case TLS1_2_VERSION:
9530
            ctx->method->version.minor = TLSv1_2_MINOR;
9531
            break;
9532
        case TLS1_3_VERSION:
9533
            ctx->method->version.minor = TLSv1_3_MINOR;
9534
            break;
9535
    #endif
9536
    #ifdef WOLFSSL_DTLS
9537
        case DTLS1_VERSION:
9538
            ctx->method->version.minor = DTLS_MINOR;
9539
            break;
9540
        case DTLS1_2_VERSION:
9541
            ctx->method->version.minor = DTLSv1_2_MINOR;
9542
            break;
9543
    #endif
9544
        default:
9545
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9546
            return WOLFSSL_FAILURE;
9547
        }
9548
    }
9549
    return ret;
9550
}
9551
9552
9553
/* Sets the max protocol version allowed with WOLFSSL_CTX
9554
 * returns WOLFSSL_SUCCESS on success */
9555
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
9556
{
9557
    int i;
9558
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
9559
    int minProto;
9560
9561
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
9562
9563
    if (ctx == NULL) {
9564
        return ret;
9565
    }
9566
9567
    /* clear out flags and reset min protocol version */
9568
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
9569
    wolfSSL_CTX_clear_options(ctx,
9570
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
9571
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
9572
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
9573
    if (version != 0) {
9574
        ctx->maxProto = 0; /* turn max proto flag off */
9575
        return Set_CTX_max_proto_version(ctx, version);
9576
    }
9577
9578
    /* when 0 is specified as version, try to find out the min version from
9579
     * the bottom to top of the protoverTbl.
9580
     */
9581
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
9582
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
9583
        if (ret == WOLFSSL_SUCCESS) {
9584
            ctx->maxProto = 1; /* turn max proto flag on */
9585
            break;
9586
        }
9587
    }
9588
9589
    return ret;
9590
}
9591
9592
9593
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
9594
{
9595
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
9596
9597
    if (ssl == NULL) {
9598
        return WOLFSSL_FAILURE;
9599
    }
9600
9601
    switch (ver) {
9602
#ifndef NO_TLS
9603
        case SSL3_VERSION:
9604
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
9605
            ssl->options.minDowngrade = SSLv3_MINOR;
9606
            break;
9607
#endif
9608
        case TLS1_VERSION:
9609
        #ifdef WOLFSSL_ALLOW_TLSV10
9610
            ssl->options.minDowngrade = TLSv1_MINOR;
9611
            break;
9612
        #endif
9613
        case TLS1_1_VERSION:
9614
        #ifndef NO_OLD_TLS
9615
            ssl->options.minDowngrade = TLSv1_1_MINOR;
9616
            break;
9617
        #endif
9618
        case TLS1_2_VERSION:
9619
        #ifndef WOLFSSL_NO_TLS12
9620
            ssl->options.minDowngrade = TLSv1_2_MINOR;
9621
            break;
9622
        #endif
9623
        case TLS1_3_VERSION:
9624
        #ifdef WOLFSSL_TLS13
9625
            ssl->options.minDowngrade = TLSv1_3_MINOR;
9626
            break;
9627
        #endif
9628
#endif
9629
#ifdef WOLFSSL_DTLS
9630
        case DTLS1_VERSION:
9631
    #ifndef NO_OLD_TLS
9632
            ssl->options.minDowngrade = DTLS_MINOR;
9633
            break;
9634
    #endif
9635
        case DTLS1_2_VERSION:
9636
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
9637
            break;
9638
#endif
9639
        default:
9640
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9641
            return WOLFSSL_FAILURE;
9642
    }
9643
9644
    switch (ver) {
9645
#ifndef NO_TLS
9646
    case TLS1_3_VERSION:
9647
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
9648
        FALL_THROUGH;
9649
    case TLS1_2_VERSION:
9650
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
9651
        FALL_THROUGH;
9652
    case TLS1_1_VERSION:
9653
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
9654
        FALL_THROUGH;
9655
    case TLS1_VERSION:
9656
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
9657
        break;
9658
    case SSL3_VERSION:
9659
    case SSL2_VERSION:
9660
        /* Nothing to do here */
9661
        break;
9662
#endif
9663
#ifdef WOLFSSL_DTLS
9664
    case DTLS1_VERSION:
9665
    case DTLS1_2_VERSION:
9666
        break;
9667
#endif
9668
    default:
9669
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9670
        return WOLFSSL_FAILURE;
9671
    }
9672
9673
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
9674
}
9675
9676
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
9677
{
9678
    int i;
9679
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
9680
9681
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
9682
9683
    if (ssl == NULL) {
9684
        return WOLFSSL_FAILURE;
9685
    }
9686
    if (version != 0) {
9687
        return Set_SSL_min_proto_version(ssl, version);
9688
    }
9689
9690
    /* when 0 is specified as version, try to find out the min version */
9691
    for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
9692
        ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
9693
        if (ret == WOLFSSL_SUCCESS)
9694
            break;
9695
    }
9696
9697
    return ret;
9698
}
9699
9700
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
9701
{
9702
9703
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
9704
9705
    if (!ssl) {
9706
        WOLFSSL_MSG("Bad parameter");
9707
        return WOLFSSL_FAILURE;
9708
    }
9709
9710
    switch (ver) {
9711
    case SSL2_VERSION:
9712
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
9713
        return WOLFSSL_FAILURE;
9714
#ifndef NO_TLS
9715
    case SSL3_VERSION:
9716
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
9717
        FALL_THROUGH;
9718
    case TLS1_VERSION:
9719
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
9720
        FALL_THROUGH;
9721
    case TLS1_1_VERSION:
9722
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
9723
        FALL_THROUGH;
9724
    case TLS1_2_VERSION:
9725
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
9726
        FALL_THROUGH;
9727
    case TLS1_3_VERSION:
9728
        /* Nothing to do here */
9729
        break;
9730
#endif
9731
#ifdef WOLFSSL_DTLS
9732
    case DTLS1_VERSION:
9733
    case DTLS1_2_VERSION:
9734
        break;
9735
#endif
9736
    default:
9737
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
9738
        return WOLFSSL_FAILURE;
9739
    }
9740
9741
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
9742
}
9743
9744
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
9745
{
9746
    int i;
9747
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
9748
9749
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
9750
9751
    if (ssl == NULL) {
9752
        return WOLFSSL_FAILURE;
9753
    }
9754
    if (version != 0) {
9755
        return Set_SSL_max_proto_version(ssl, version);
9756
    }
9757
9758
    /* when 0 is specified as version, try to find out the min version from
9759
     * the bottom to top of the protoverTbl.
9760
     */
9761
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
9762
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
9763
        if (ret == WOLFSSL_SUCCESS)
9764
            break;
9765
    }
9766
9767
    return ret;
9768
}
9769
9770
static int GetMinProtoVersion(int minDowngrade)
9771
{
9772
    int ret;
9773
9774
    switch (minDowngrade) {
9775
#ifndef NO_OLD_TLS
9776
    #ifdef WOLFSSL_ALLOW_SSLV3
9777
        case SSLv3_MINOR:
9778
            ret = SSL3_VERSION;
9779
            break;
9780
    #endif
9781
    #ifdef WOLFSSL_ALLOW_TLSV10
9782
        case TLSv1_MINOR:
9783
            ret = TLS1_VERSION;
9784
            break;
9785
    #endif
9786
        case TLSv1_1_MINOR:
9787
            ret = TLS1_1_VERSION;
9788
            break;
9789
#endif
9790
#ifndef WOLFSSL_NO_TLS12
9791
        case TLSv1_2_MINOR:
9792
            ret = TLS1_2_VERSION;
9793
            break;
9794
#endif
9795
#ifdef WOLFSSL_TLS13
9796
        case TLSv1_3_MINOR:
9797
            ret = TLS1_3_VERSION;
9798
            break;
9799
#endif
9800
        default:
9801
            ret = 0;
9802
            break;
9803
    }
9804
9805
    return ret;
9806
}
9807
9808
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
9809
{
9810
    int ret = 0;
9811
9812
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
9813
9814
    if (ctx != NULL) {
9815
        if (ctx->minProto) {
9816
            ret = 0;
9817
        }
9818
        else {
9819
            ret = GetMinProtoVersion(ctx->minDowngrade);
9820
        }
9821
    }
9822
    else {
9823
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
9824
    }
9825
9826
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
9827
9828
    return ret;
9829
}
9830
9831
9832
/* returns the maximum allowed protocol version given the 'options' used
9833
 * returns WOLFSSL_FATAL_ERROR on no match */
9834
static int GetMaxProtoVersion(long options)
9835
{
9836
#ifndef NO_TLS
9837
#ifdef WOLFSSL_TLS13
9838
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
9839
        return TLS1_3_VERSION;
9840
#endif
9841
#ifndef WOLFSSL_NO_TLS12
9842
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
9843
        return TLS1_2_VERSION;
9844
#endif
9845
#ifndef NO_OLD_TLS
9846
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
9847
        return TLS1_1_VERSION;
9848
    #ifdef WOLFSSL_ALLOW_TLSV10
9849
    if (!(options & WOLFSSL_OP_NO_TLSv1))
9850
        return TLS1_VERSION;
9851
    #endif
9852
    #ifdef WOLFSSL_ALLOW_SSLV3
9853
    if (!(options & WOLFSSL_OP_NO_SSLv3))
9854
        return SSL3_VERSION;
9855
    #endif
9856
#endif
9857
#else
9858
    (void)options;
9859
#endif /* NO_TLS */
9860
    return WOLFSSL_FATAL_ERROR;
9861
}
9862
9863
9864
/* returns the maximum protocol version for 'ctx' */
9865
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
9866
{
9867
    int ret = 0;
9868
    long options = 0; /* default to nothing set */
9869
9870
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
9871
9872
    if (ctx != NULL) {
9873
        options = wolfSSL_CTX_get_options(ctx);
9874
    }
9875
9876
    if ((ctx != NULL) && ctx->maxProto) {
9877
        ret = 0;
9878
    }
9879
    else {
9880
        ret = GetMaxProtoVersion(options);
9881
    }
9882
9883
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
9884
9885
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
9886
        WOLFSSL_MSG("Error getting max proto version");
9887
        ret = 0; /* setting ret to 0 to match compat return */
9888
    }
9889
    return ret;
9890
}
9891
#endif /* OPENSSL_EXTRA */
9892
9893
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
9894
    defined(HAVE_SECRET_CALLBACK)
9895
#if !defined(NO_WOLFSSL_CLIENT)
9896
/* Return the amount of random bytes copied over or error case.
9897
 * ssl : ssl struct after handshake
9898
 * out : buffer to hold random bytes
9899
 * outSz : either 0 (return max buffer sz) or size of out buffer
9900
 */
9901
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
9902
                                                                   size_t outSz)
9903
{
9904
    size_t size;
9905
9906
    /* return max size of buffer */
9907
    if (outSz == 0) {
9908
        return RAN_LEN;
9909
    }
9910
9911
    if (ssl == NULL || out == NULL) {
9912
        return 0;
9913
    }
9914
9915
    if (ssl->arrays == NULL) {
9916
        WOLFSSL_MSG("Arrays struct not saved after handshake");
9917
        return 0;
9918
    }
9919
9920
    if (outSz > RAN_LEN) {
9921
        size = RAN_LEN;
9922
    }
9923
    else {
9924
        size = outSz;
9925
    }
9926
9927
    XMEMCPY(out, ssl->arrays->clientRandom, size);
9928
    return size;
9929
}
9930
#endif /* !NO_WOLFSSL_CLIENT */
9931
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
9932
9933
#ifdef OPENSSL_EXTRA
9934
9935
    unsigned long wolfSSLeay(void)
9936
    {
9937
#ifdef SSLEAY_VERSION_NUMBER
9938
        return SSLEAY_VERSION_NUMBER;
9939
#else
9940
        return OPENSSL_VERSION_NUMBER;
9941
#endif
9942
    }
9943
9944
    unsigned long wolfSSL_OpenSSL_version_num(void)
9945
    {
9946
        return OPENSSL_VERSION_NUMBER;
9947
    }
9948
9949
    const char* wolfSSLeay_version(int type)
9950
    {
9951
        (void)type;
9952
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
9953
        return wolfSSL_OpenSSL_version(type);
9954
#else
9955
        return wolfSSL_OpenSSL_version();
9956
#endif
9957
    }
9958
#endif /* OPENSSL_EXTRA */
9959
9960
#ifdef OPENSSL_EXTRA
9961
    void wolfSSL_ERR_free_strings(void)
9962
    {
9963
        /* handled internally */
9964
    }
9965
9966
    void wolfSSL_cleanup_all_ex_data(void)
9967
    {
9968
        /* nothing to do here */
9969
    }
9970
9971
#endif /* OPENSSL_EXTRA */
9972
9973
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
9974
    defined(HAVE_CURL)
9975
    void wolfSSL_ERR_clear_error(void)
9976
    {
9977
        WOLFSSL_ENTER("wolfSSL_ERR_clear_error");
9978
    #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
9979
        wc_ClearErrorNodes();
9980
    #endif
9981
    }
9982
#endif
9983
9984
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
9985
    int wolfSSL_clear(WOLFSSL* ssl)
9986
    {
9987
        WOLFSSL_ENTER("wolfSSL_clear");
9988
9989
        if (ssl == NULL) {
9990
            return WOLFSSL_FAILURE;
9991
        }
9992
9993
        if (!ssl->options.handShakeDone) {
9994
            /* Only reset the session if we didn't complete a handshake */
9995
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
9996
            ssl->session = wolfSSL_NewSession(ssl->heap);
9997
            if (ssl->session == NULL) {
9998
                return WOLFSSL_FAILURE;
9999
            }
10000
        }
10001
10002
        /* reset error */
10003
        ssl->error = 0;
10004
10005
        /* reset option bits */
10006
        ssl->options.isClosed = 0;
10007
        ssl->options.connReset = 0;
10008
        ssl->options.sentNotify = 0;
10009
        ssl->options.closeNotify = 0;
10010
        ssl->options.sendVerify = 0;
10011
        ssl->options.serverState = NULL_STATE;
10012
        ssl->options.clientState = NULL_STATE;
10013
        ssl->options.connectState = CONNECT_BEGIN;
10014
        ssl->options.acceptState  = ACCEPT_BEGIN;
10015
        ssl->options.handShakeState  = NULL_STATE;
10016
        ssl->options.handShakeDone = 0;
10017
        ssl->options.processReply = 0; /* doProcessInit */
10018
        ssl->options.havePeerVerify = 0;
10019
        ssl->options.havePeerCert = 0;
10020
        ssl->options.peerAuthGood = 0;
10021
        ssl->options.tls1_3 = 0;
10022
        ssl->options.haveSessionId = 0;
10023
        ssl->options.tls = 0;
10024
        ssl->options.tls1_1 = 0;
10025
    #ifdef WOLFSSL_TLS13
10026
    #ifdef WOLFSSL_SEND_HRR_COOKIE
10027
        ssl->options.hrrSentCookie = 0;
10028
    #endif
10029
        ssl->options.hrrSentKeyShare = 0;
10030
    #endif
10031
    #ifdef WOLFSSL_DTLS
10032
        ssl->options.dtlsStateful = 0;
10033
    #endif
10034
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
10035
        ssl->options.noPskDheKe = 0;
10036
      #ifdef HAVE_SUPPORTED_CURVES
10037
        ssl->options.onlyPskDheKe = 0;
10038
      #endif
10039
    #endif
10040
    #ifdef HAVE_SESSION_TICKET
10041
        #ifdef WOLFSSL_TLS13
10042
        ssl->options.ticketsSent = 0;
10043
        #endif
10044
        ssl->options.rejectTicket = 0;
10045
    #endif
10046
    #ifdef WOLFSSL_EARLY_DATA
10047
        ssl->earlyData = no_early_data;
10048
        ssl->earlyDataSz = 0;
10049
    #endif
10050
10051
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
10052
        TLSX_FreeAll(ssl->extensions, ssl->heap);
10053
        ssl->extensions = NULL;
10054
    #endif
10055
10056
        if (ssl->keys.encryptionOn) {
10057
            ForceZero(ssl->buffers.inputBuffer.buffer -
10058
                ssl->buffers.inputBuffer.offset,
10059
                ssl->buffers.inputBuffer.bufferSize);
10060
        #ifdef WOLFSSL_CHECK_MEM_ZERO
10061
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
10062
                ssl->buffers.inputBuffer.offset,
10063
                ssl->buffers.inputBuffer.bufferSize);
10064
        #endif
10065
        }
10066
        ssl->keys.encryptionOn = 0;
10067
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
10068
10069
        FreeCiphers(ssl);
10070
        InitCiphers(ssl);
10071
        InitCipherSpecs(&ssl->specs);
10072
10073
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
10074
            return WOLFSSL_FAILURE;
10075
10076
        if (InitHandshakeHashes(ssl) != 0)
10077
            return WOLFSSL_FAILURE;
10078
10079
#ifdef KEEP_PEER_CERT
10080
        FreeX509(&ssl->peerCert);
10081
        InitX509(&ssl->peerCert, 0, ssl->heap);
10082
#endif
10083
10084
#ifdef WOLFSSL_QUIC
10085
        wolfSSL_quic_clear(ssl);
10086
#endif
10087
#ifdef HAVE_OCSP
10088
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
10089
        ssl->response_idx = 0;
10090
#endif
10091
#endif
10092
        return WOLFSSL_SUCCESS;
10093
    }
10094
10095
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
10096
10097
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
10098
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
10099
    {
10100
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
10101
10102
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
10103
        switch(mode) {
10104
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
10105
                ctx->partialWrite = 1;
10106
                break;
10107
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
10108
            case SSL_MODE_RELEASE_BUFFERS:
10109
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
10110
                break;
10111
            #endif
10112
            case WOLFSSL_MODE_AUTO_RETRY:
10113
                ctx->autoRetry = 1;
10114
                break;
10115
            default:
10116
                WOLFSSL_MSG("Mode Not Implemented");
10117
        }
10118
10119
        /* WOLFSSL_MODE_AUTO_RETRY
10120
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
10121
10122
        return mode;
10123
    }
10124
10125
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
10126
    {
10127
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
10128
10129
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
10130
        switch(mode) {
10131
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
10132
                ctx->partialWrite = 0;
10133
                break;
10134
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
10135
            case SSL_MODE_RELEASE_BUFFERS:
10136
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
10137
                break;
10138
            #endif
10139
            case WOLFSSL_MODE_AUTO_RETRY:
10140
                ctx->autoRetry = 0;
10141
                break;
10142
            default:
10143
                WOLFSSL_MSG("Mode Not Implemented");
10144
        }
10145
10146
        /* WOLFSSL_MODE_AUTO_RETRY
10147
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
10148
10149
        return 0;
10150
    }
10151
#endif
10152
10153
#ifdef OPENSSL_EXTRA
10154
10155
    #ifndef NO_WOLFSSL_STUB
10156
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
10157
    {
10158
        /* TODO: */
10159
        (void)ssl;
10160
        WOLFSSL_STUB("SSL_get_mode");
10161
        return 0;
10162
    }
10163
    #endif
10164
10165
    #ifndef NO_WOLFSSL_STUB
10166
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
10167
    {
10168
        /* TODO: */
10169
        (void)ctx;
10170
        WOLFSSL_STUB("SSL_CTX_get_mode");
10171
        return 0;
10172
    }
10173
    #endif
10174
10175
    #ifndef NO_WOLFSSL_STUB
10176
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
10177
    {
10178
        /* TODO: maybe? */
10179
        (void)ctx;
10180
        (void)m;
10181
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
10182
    }
10183
    #endif
10184
10185
10186
    /* returns the unsigned error value and increments the pointer into the
10187
     * error queue.
10188
     *
10189
     * file  pointer to file name
10190
     * line  gets set to line number of error when not NULL
10191
     */
10192
    unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line)
10193
    {
10194
    #ifdef WOLFSSL_HAVE_ERROR_QUEUE
10195
        int ret = wc_PullErrorNode(file, NULL, line);
10196
        if (ret < 0) {
10197
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
10198
                return 0; /* no errors in queue */
10199
            WOLFSSL_MSG("Issue getting error node");
10200
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret);
10201
            ret = 0 - ret; /* return absolute value of error */
10202
10203
            /* panic and try to clear out nodes */
10204
            wc_ClearErrorNodes();
10205
        }
10206
        return (unsigned long)ret;
10207
    #else
10208
        (void)file;
10209
        (void)line;
10210
10211
        return 0;
10212
    #endif
10213
    }
10214
10215
10216
#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \
10217
    (!defined(_WIN32) && !defined(NO_ERROR_QUEUE))
10218
    static const char WOLFSSL_SYS_ACCEPT_T[]  = "accept";
10219
    static const char WOLFSSL_SYS_BIND_T[]    = "bind";
10220
    static const char WOLFSSL_SYS_CONNECT_T[] = "connect";
10221
    static const char WOLFSSL_SYS_FOPEN_T[]   = "fopen";
10222
    static const char WOLFSSL_SYS_FREAD_T[]   = "fread";
10223
    static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo";
10224
    static const char WOLFSSL_SYS_GETSOCKOPT_T[]  = "getsockopt";
10225
    static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname";
10226
    static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname";
10227
    static const char WOLFSSL_SYS_GETNAMEINFO_T[]   = "getnameinfo";
10228
    static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname";
10229
    static const char WOLFSSL_SYS_IOCTLSOCKET_T[]   = "ioctlsocket";
10230
    static const char WOLFSSL_SYS_LISTEN_T[]        = "listen";
10231
    static const char WOLFSSL_SYS_OPENDIR_T[]       = "opendir";
10232
    static const char WOLFSSL_SYS_SETSOCKOPT_T[]    = "setsockopt";
10233
    static const char WOLFSSL_SYS_SOCKET_T[]        = "socket";
10234
10235
    /* switch with int mapped to function name for compatibility */
10236
    static const char* wolfSSL_ERR_sys_func(int fun)
10237
    {
10238
        switch (fun) {
10239
            case WOLFSSL_SYS_ACCEPT:      return WOLFSSL_SYS_ACCEPT_T;
10240
            case WOLFSSL_SYS_BIND:        return WOLFSSL_SYS_BIND_T;
10241
            case WOLFSSL_SYS_CONNECT:     return WOLFSSL_SYS_CONNECT_T;
10242
            case WOLFSSL_SYS_FOPEN:       return WOLFSSL_SYS_FOPEN_T;
10243
            case WOLFSSL_SYS_FREAD:       return WOLFSSL_SYS_FREAD_T;
10244
            case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T;
10245
            case WOLFSSL_SYS_GETSOCKOPT:  return WOLFSSL_SYS_GETSOCKOPT_T;
10246
            case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T;
10247
            case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T;
10248
            case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T;
10249
            case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T;
10250
            case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T;
10251
            case WOLFSSL_SYS_LISTEN:      return WOLFSSL_SYS_LISTEN_T;
10252
            case WOLFSSL_SYS_OPENDIR:     return WOLFSSL_SYS_OPENDIR_T;
10253
            case WOLFSSL_SYS_SETSOCKOPT:  return WOLFSSL_SYS_SETSOCKOPT_T;
10254
            case WOLFSSL_SYS_SOCKET:      return WOLFSSL_SYS_SOCKET_T;
10255
            default:
10256
                return "NULL";
10257
        }
10258
    }
10259
#endif /* DEBUG_WOLFSSL */
10260
10261
10262
    void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file,
10263
            int line)
10264
    {
10265
        WOLFSSL_ENTER("wolfSSL_ERR_put_error");
10266
10267
        #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA)
10268
        (void)fun;
10269
        (void)err;
10270
        (void)file;
10271
        (void)line;
10272
        WOLFSSL_MSG("Not compiled in debug mode");
10273
        #elif defined(OPENSSL_EXTRA) && \
10274
                (defined(_WIN32) || defined(NO_ERROR_QUEUE))
10275
        (void)fun;
10276
        (void)file;
10277
        (void)line;
10278
        WOLFSSL_ERROR(err);
10279
        #else
10280
        WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line,
10281
            file, NULL);
10282
        #endif
10283
        (void)lib;
10284
    }
10285
10286
10287
    /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for
10288
     * more flexibility.
10289
     *
10290
     * file  output pointer to file where error happened
10291
     * line  output to line number of error
10292
     * data  output data. Is a string if WOLFSSL_ERR_TXT_STRING flag is used
10293
     * flags output format of output
10294
     *
10295
     * Returns the error value or 0 if no errors are in the queue
10296
     */
10297
    unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line,
10298
                                                  const char** data, int *flags)
10299
    {
10300
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
10301
        int ret;
10302
10303
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
10304
10305
        if (flags != NULL)
10306
            *flags = WOLFSSL_ERR_TXT_STRING; /* Clear the flags */
10307
10308
        ret = wc_PullErrorNode(file, data, line);
10309
        if (ret < 0) {
10310
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
10311
                return 0; /* no errors in queue */
10312
            WOLFSSL_MSG("Error with pulling error node!");
10313
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret);
10314
            ret = 0 - ret; /* return absolute value of error */
10315
10316
            /* panic and try to clear out nodes */
10317
            wc_ClearErrorNodes();
10318
        }
10319
10320
        return (unsigned long)ret;
10321
#else
10322
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
10323
        WOLFSSL_MSG("Error queue turned off, can not get error line");
10324
        (void)file;
10325
        (void)line;
10326
        (void)data;
10327
        (void)flags;
10328
        return 0;
10329
#endif
10330
    }
10331
10332
#endif /* OPENSSL_EXTRA */
10333
10334
10335
#if (defined(KEEP_PEER_CERT) && defined(SESSION_CERTS)) || \
10336
    (defined(OPENSSL_EXTRA) && defined(SESSION_CERTS))
10337
    /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object.
10338
     *
10339
     * x509  WOLFSSL_X509 object to decode into.
10340
     * in    X509 DER data.
10341
     * len   Length of the X509 DER data.
10342
     * returns the new certificate on success, otherwise NULL.
10343
     */
10344
    static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len)
10345
    {
10346
        int          ret;
10347
        WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
10348
        if (x509 == NULL || in == NULL || len <= 0)
10349
            return BAD_FUNC_ARG;
10350
10351
        WC_ALLOC_VAR_EX(cert, DecodedCert, 1, NULL, DYNAMIC_TYPE_DCERT,
10352
            return MEMORY_E);
10353
10354
        /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object.
10355
         */
10356
        InitDecodedCert(cert, (byte*)in, (word32)len, NULL);
10357
        if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) == 0) {
10358
        /* Check if x509 was not previously initialized by wolfSSL_X509_new() */
10359
            if (x509->dynamicMemory != TRUE)
10360
                InitX509(x509, 0, NULL);
10361
            ret = CopyDecodedToX509(x509, cert);
10362
        }
10363
        FreeDecodedCert(cert);
10364
        WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
10365
10366
        return ret;
10367
    }
10368
#endif /* (KEEP_PEER_CERT & SESSION_CERTS) || (OPENSSL_EXTRA & SESSION_CERTS) */
10369
10370
10371
#ifdef KEEP_PEER_CERT
10372
    WOLFSSL_ABI
10373
    WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl)
10374
    {
10375
        WOLFSSL_X509* ret = NULL;
10376
        WOLFSSL_ENTER("wolfSSL_get_peer_certificate");
10377
        if (ssl != NULL) {
10378
            if (ssl->peerCert.issuer.sz)
10379
                ret = wolfSSL_X509_dup(&ssl->peerCert);
10380
#ifdef SESSION_CERTS
10381
            else if (ssl->session->chain.count > 0) {
10382
                if (DecodeToX509(&ssl->peerCert,
10383
                        ssl->session->chain.certs[0].buffer,
10384
                        ssl->session->chain.certs[0].length) == 0) {
10385
                    ret = wolfSSL_X509_dup(&ssl->peerCert);
10386
                }
10387
            }
10388
#endif
10389
        }
10390
        WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL);
10391
        return ret;
10392
    }
10393
10394
#endif /* KEEP_PEER_CERT */
10395
10396
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
10397
/* Return stack of peer certs.
10398
 * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl
10399
 * is.
10400
 */
10401
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl)
10402
{
10403
    WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain");
10404
10405
    if (ssl == NULL)
10406
        return NULL;
10407
10408
    /* Try to populate if NULL or empty */
10409
    if (ssl->peerCertChain == NULL ||
10410
            wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) {
10411
        wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl);
10412
    }
10413
    return ssl->peerCertChain;
10414
}
10415
10416
10417
static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
10418
        WOLFSSL_X509 *x);
10419
/**
10420
 * Recursively push the issuer CA chain onto the stack
10421
 * @param cm The cert manager that is queried for the issuer
10422
 * @param x  This cert's issuer will be queried in cm
10423
 * @param sk The issuer is pushed onto this stack
10424
 * @return 0 on success or no issuer found
10425
 *         WOLFSSL_FATAL_ERROR on a fatal error
10426
 */
10427
static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm,
10428
        WOLFSSL_X509 *x, WOLFSSL_STACK* sk)
10429
{
10430
    int i;
10431
    for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
10432
        WOLFSSL_X509* issuer = NULL;
10433
        if (x509GetIssuerFromCM(&issuer, cm, x) != WOLFSSL_SUCCESS)
10434
            break;
10435
        if (wolfSSL_sk_X509_push(sk, issuer) <= 0) {
10436
            wolfSSL_X509_free(issuer);
10437
            issuer = NULL;
10438
            return WOLFSSL_FATAL_ERROR;
10439
        }
10440
        x = issuer;
10441
    }
10442
    return 0;
10443
}
10444
10445
10446
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
10447
    or ssl->verifiedChain based off of the ssl session chain. Attempts to place
10448
    CA certificates at the bottom of the stack for a verified chain. Returns
10449
    stack of WOLFSSL_X509 certs or NULL on failure */
10450
static WOLF_STACK_OF(WOLFSSL_X509)* CreatePeerCertChain(const WOLFSSL* ssl,
10451
    int verifiedFlag)
10452
{
10453
    WOLFSSL_STACK* sk;
10454
    WOLFSSL_X509* x509;
10455
    int i = 0;
10456
    int err;
10457
10458
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
10459
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
10460
        return NULL;
10461
10462
    sk = wolfSSL_sk_X509_new_null();
10463
    for (i = 0; i < ssl->session->chain.count; i++) {
10464
        x509 = wolfSSL_X509_new_ex(ssl->heap);
10465
        if (x509 == NULL) {
10466
            WOLFSSL_MSG("Error Creating X509");
10467
            wolfSSL_sk_X509_pop_free(sk, NULL);
10468
            return NULL;
10469
        }
10470
        err = DecodeToX509(x509, ssl->session->chain.certs[i].buffer,
10471
                             ssl->session->chain.certs[i].length);
10472
        if (err == 0 && wolfSSL_sk_X509_push(sk, x509) <= 0)
10473
            err = WOLFSSL_FATAL_ERROR;
10474
        if (err == 0 && i == ssl->session->chain.count-1 && verifiedFlag) {
10475
            /* On the last element in the verified chain try to add the CA chain
10476
             * if we have one for this cert */
10477
            SSL_CM_WARNING(ssl);
10478
            err = PushCAx509Chain(SSL_CM(ssl), x509, sk);
10479
        }
10480
        if (err != 0) {
10481
            WOLFSSL_MSG("Error decoding cert");
10482
            wolfSSL_X509_free(x509);
10483
            x509 = NULL;
10484
            wolfSSL_sk_X509_pop_free(sk, NULL);
10485
            return NULL;
10486
        }
10487
    }
10488
10489
    if (sk == NULL) {
10490
        WOLFSSL_MSG("Null session chain");
10491
    }
10492
    return sk;
10493
}
10494
10495
10496
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
10497
    returns the stack on success and NULL on failure */
10498
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl)
10499
{
10500
    WOLFSSL_STACK* sk;
10501
10502
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
10503
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
10504
        return NULL;
10505
10506
    sk = CreatePeerCertChain(ssl, 0);
10507
10508
    if (sk != NULL) {
10509
        if (ssl->options.side == WOLFSSL_SERVER_END) {
10510
            if (ssl->session->peer)
10511
                wolfSSL_X509_free(ssl->session->peer);
10512
10513
            ssl->session->peer = wolfSSL_sk_X509_shift(sk);
10514
            ssl->session->peerVerifyRet = ssl->peerVerifyRet;
10515
        }
10516
        if (ssl->peerCertChain != NULL)
10517
            wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
10518
        /* This is Free'd when ssl is Free'd */
10519
        ssl->peerCertChain = sk;
10520
    }
10521
    return sk;
10522
}
10523
10524
#ifdef KEEP_PEER_CERT
10525
/**
10526
 * Implemented in a similar way that ngx_ssl_ocsp_validate does it when
10527
 * SSL_get0_verified_chain is not available.
10528
 * @param ssl WOLFSSL object to extract certs from
10529
 * @return Stack of verified certs
10530
 */
10531
WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl)
10532
{
10533
    WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL;
10534
    WOLFSSL_X509_STORE_CTX* storeCtx = NULL;
10535
    WOLFSSL_X509* peerCert = NULL;
10536
10537
    WOLFSSL_ENTER("wolfSSL_get0_verified_chain");
10538
10539
    if (ssl == NULL || ssl->ctx == NULL) {
10540
        WOLFSSL_MSG("Bad parameter");
10541
        return NULL;
10542
    }
10543
10544
    peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl);
10545
    if (peerCert == NULL) {
10546
        WOLFSSL_MSG("wolfSSL_get_peer_certificate error");
10547
        return NULL;
10548
    }
10549
    /* wolfSSL_get_peer_certificate returns a copy. We want the internal
10550
     * member so that we don't have to worry about free'ing it. We call
10551
     * wolfSSL_get_peer_certificate so that we don't have to worry about
10552
     * setting up the internal pointer. */
10553
    wolfSSL_X509_free(peerCert);
10554
    peerCert = (WOLFSSL_X509*)&ssl->peerCert;
10555
    chain = CreatePeerCertChain((WOLFSSL*)ssl, 1);
10556
    if (chain == NULL) {
10557
        WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error");
10558
        return NULL;
10559
    }
10560
10561
    if (ssl->verifiedChain != NULL) {
10562
        wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL);
10563
    }
10564
    ((WOLFSSL*)ssl)->verifiedChain = chain;
10565
10566
    storeCtx = wolfSSL_X509_STORE_CTX_new();
10567
    if (storeCtx == NULL) {
10568
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error");
10569
        return NULL;
10570
    }
10571
    if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl),
10572
            peerCert, chain) != WOLFSSL_SUCCESS) {
10573
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error");
10574
        wolfSSL_X509_STORE_CTX_free(storeCtx);
10575
        return NULL;
10576
    }
10577
    if (wolfSSL_X509_verify_cert(storeCtx) <= 0) {
10578
        WOLFSSL_MSG("wolfSSL_X509_verify_cert error");
10579
        wolfSSL_X509_STORE_CTX_free(storeCtx);
10580
        return NULL;
10581
    }
10582
    wolfSSL_X509_STORE_CTX_free(storeCtx);
10583
    return chain;
10584
}
10585
#endif /* KEEP_PEER_CERT */
10586
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
10587
10588
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
10589
void wolfSSL_set_connect_state(WOLFSSL* ssl)
10590
{
10591
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
10592
    if (ssl == NULL) {
10593
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
10594
        return;
10595
    }
10596
10597
    #ifndef NO_DH
10598
    /* client creates its own DH parameters on handshake */
10599
    if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
10600
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
10601
            DYNAMIC_TYPE_PUBLIC_KEY);
10602
    }
10603
    ssl->buffers.serverDH_P.buffer = NULL;
10604
    if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
10605
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
10606
            DYNAMIC_TYPE_PUBLIC_KEY);
10607
    }
10608
    ssl->buffers.serverDH_G.buffer = NULL;
10609
    #endif
10610
10611
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
10612
        WOLFSSL_MSG("Error initializing client side");
10613
    }
10614
}
10615
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
10616
10617
10618
int wolfSSL_get_shutdown(const WOLFSSL* ssl)
10619
0
{
10620
0
    int isShutdown = 0;
10621
10622
0
    WOLFSSL_ENTER("wolfSSL_get_shutdown");
10623
10624
0
    if (ssl) {
10625
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
10626
        if (ssl->options.shutdownDone) {
10627
            /* The SSL object was possibly cleared with wolfSSL_clear after
10628
             * a successful shutdown. Simulate a response for a full
10629
             * bidirectional shutdown. */
10630
            isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN;
10631
        }
10632
        else
10633
#endif
10634
0
        {
10635
            /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent   *
10636
             * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */
10637
0
            if (ssl->options.sentNotify)
10638
0
                isShutdown |= WOLFSSL_SENT_SHUTDOWN;
10639
0
            if (ssl->options.closeNotify||ssl->options.connReset)
10640
0
                isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN;
10641
0
        }
10642
10643
0
    }
10644
10645
0
    WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown);
10646
0
    return isShutdown;
10647
0
}
10648
10649
10650
int wolfSSL_session_reused(WOLFSSL* ssl)
10651
0
{
10652
0
    int resuming = 0;
10653
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
10654
0
    if (ssl) {
10655
0
#ifndef HAVE_SECURE_RENEGOTIATION
10656
0
        resuming = ssl->options.resuming;
10657
#else
10658
        resuming = ssl->options.resuming || ssl->options.resumed;
10659
#endif
10660
0
    }
10661
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
10662
0
    return resuming;
10663
0
}
10664
10665
/* helper function that takes in a protocol version struct and returns string */
10666
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
10667
0
{
10668
0
    WOLFSSL_ENTER("wolfSSL_get_version");
10669
10670
0
    if (version == NULL) {
10671
0
        return "Bad arg";
10672
0
    }
10673
10674
0
    if (version->major == SSLv3_MAJOR) {
10675
0
        switch (version->minor) {
10676
0
            case SSLv3_MINOR :
10677
0
                return "SSLv3";
10678
0
            case TLSv1_MINOR :
10679
0
                return "TLSv1";
10680
0
            case TLSv1_1_MINOR :
10681
0
                return "TLSv1.1";
10682
0
            case TLSv1_2_MINOR :
10683
0
                return "TLSv1.2";
10684
0
            case TLSv1_3_MINOR :
10685
0
                return "TLSv1.3";
10686
0
            default:
10687
0
                return "unknown";
10688
0
        }
10689
0
    }
10690
#ifdef WOLFSSL_DTLS
10691
    else if (version->major == DTLS_MAJOR) {
10692
        switch (version->minor) {
10693
            case DTLS_MINOR :
10694
                return "DTLS";
10695
            case DTLSv1_2_MINOR :
10696
                return "DTLSv1.2";
10697
            case DTLSv1_3_MINOR :
10698
                return "DTLSv1.3";
10699
            default:
10700
                return "unknown";
10701
        }
10702
    }
10703
#endif /* WOLFSSL_DTLS */
10704
0
    return "unknown";
10705
0
}
10706
10707
10708
const char* wolfSSL_get_version(const WOLFSSL* ssl)
10709
0
{
10710
0
    if (ssl == NULL) {
10711
0
        WOLFSSL_MSG("Bad argument");
10712
0
        return "unknown";
10713
0
    }
10714
10715
0
    return wolfSSL_internal_get_version(&ssl->version);
10716
0
}
10717
10718
10719
/* current library version */
10720
const char* wolfSSL_lib_version(void)
10721
0
{
10722
0
    return LIBWOLFSSL_VERSION_STRING;
10723
0
}
10724
10725
#ifdef OPENSSL_EXTRA
10726
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
10727
const char* wolfSSL_OpenSSL_version(int a)
10728
{
10729
    (void)a;
10730
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
10731
}
10732
#else
10733
const char* wolfSSL_OpenSSL_version(void)
10734
{
10735
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
10736
}
10737
#endif /* WOLFSSL_QT */
10738
#endif
10739
10740
10741
/* current library version in hex */
10742
word32 wolfSSL_lib_version_hex(void)
10743
0
{
10744
0
    return LIBWOLFSSL_VERSION_HEX;
10745
0
}
10746
10747
10748
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
10749
0
{
10750
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
10751
0
    if (ssl)
10752
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
10753
0
    return 0;
10754
0
}
10755
10756
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
10757
0
{
10758
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
10759
0
    if (ssl) {
10760
0
        ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
10761
0
        ssl->cipher.cipherSuite  = ssl->options.cipherSuite;
10762
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
10763
        ssl->cipher.bits = ssl->specs.key_size * 8;
10764
#endif
10765
0
        return &ssl->cipher;
10766
0
    }
10767
0
    else
10768
0
        return NULL;
10769
0
}
10770
10771
10772
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
10773
0
{
10774
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
10775
10776
0
    if (cipher == NULL) {
10777
0
        return NULL;
10778
0
    }
10779
10780
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
10781
0
        !defined(WOLFSSL_QT)
10782
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
10783
    #else
10784
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
10785
                cipher->cipherSuite);
10786
    #endif
10787
0
}
10788
10789
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
10790
0
{
10791
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
10792
10793
0
    if (cipher == NULL || cipher->ssl == NULL) {
10794
0
        return NULL;
10795
0
    }
10796
10797
0
    return wolfSSL_get_version(cipher->ssl);
10798
0
}
10799
10800
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
10801
0
{
10802
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
10803
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
10804
0
}
10805
10806
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
10807
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
10808
0
{
10809
    /* get access to cipher_name_idx in internal.c */
10810
0
    return wolfSSL_get_cipher_name_internal(ssl);
10811
0
}
10812
10813
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
10814
    byte cipherSuite)
10815
0
{
10816
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
10817
0
}
10818
10819
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
10820
        byte cipherSuite)
10821
0
{
10822
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
10823
0
}
10824
10825
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
10826
0
                                       byte* cipherSuite, int *flags) {
10827
0
    if ((name == NULL) ||
10828
0
        (cipherSuite0 == NULL) ||
10829
0
        (cipherSuite == NULL) ||
10830
0
        (flags == NULL))
10831
0
        return BAD_FUNC_ARG;
10832
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
10833
0
                                  flags);
10834
0
}
10835
10836
10837
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
10838
0
{
10839
0
    word16 cipher_id = 0;
10840
10841
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
10842
10843
0
    if (cipher && cipher->ssl) {
10844
0
        cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) |
10845
0
                     cipher->ssl->options.cipherSuite;
10846
0
    }
10847
10848
0
    return cipher_id;
10849
0
}
10850
10851
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
10852
0
{
10853
0
    const WOLFSSL_CIPHER* cipher = NULL;
10854
0
    byte cipherSuite0, cipherSuite;
10855
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
10856
10857
    /* extract cipher id information */
10858
0
    cipherSuite =   (value       & 0xFF);
10859
0
    cipherSuite0 = ((value >> 8) & 0xFF);
10860
10861
    /* TODO: lookup by cipherSuite0 / cipherSuite */
10862
0
    (void)cipherSuite0;
10863
0
    (void)cipherSuite;
10864
10865
0
    return cipher;
10866
0
}
10867
10868
10869
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
10870
                                                                 !defined(NO_DH)
10871
#ifdef HAVE_FFDHE
10872
static const char* wolfssl_ffdhe_name(word16 group)
10873
0
{
10874
0
    const char* str = NULL;
10875
0
    switch (group) {
10876
0
        case WOLFSSL_FFDHE_2048:
10877
0
            str = "FFDHE_2048";
10878
0
            break;
10879
0
        case WOLFSSL_FFDHE_3072:
10880
0
            str = "FFDHE_3072";
10881
0
            break;
10882
0
        case WOLFSSL_FFDHE_4096:
10883
0
            str = "FFDHE_4096";
10884
0
            break;
10885
0
        case WOLFSSL_FFDHE_6144:
10886
0
            str = "FFDHE_6144";
10887
0
            break;
10888
0
        case WOLFSSL_FFDHE_8192:
10889
0
            str = "FFDHE_8192";
10890
0
            break;
10891
0
        default:
10892
0
            break;
10893
0
    }
10894
0
    return str;
10895
0
}
10896
#endif
10897
/* Return the name of the curve used for key exchange as a printable string.
10898
 *
10899
 * ssl  The SSL/TLS object.
10900
 * returns NULL if ECDH was not used, otherwise the name as a string.
10901
 */
10902
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
10903
0
{
10904
0
    const char* cName = NULL;
10905
10906
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
10907
10908
0
    if (ssl == NULL)
10909
0
        return NULL;
10910
10911
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
10912
    /* Check for post-quantum groups. Return now because we do not want the ECC
10913
     * check to override this result in the case of a hybrid. */
10914
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
10915
0
        switch (ssl->namedGroup) {
10916
0
#ifndef WOLFSSL_NO_ML_KEM
10917
0
#if defined(WOLFSSL_WC_MLKEM)
10918
0
    #ifndef WOLFSSL_NO_ML_KEM_512
10919
0
        case WOLFSSL_ML_KEM_512:
10920
0
            return "ML_KEM_512";
10921
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
10922
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
10923
        case WOLFSSL_P256_ML_KEM_512_OLD:
10924
            return "P256_ML_KEM_512_OLD";
10925
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
10926
        case WOLFSSL_SECP256R1MLKEM512:
10927
            return "SecP256r1MLKEM512";
10928
        #ifdef HAVE_CURVE25519
10929
        case WOLFSSL_X25519MLKEM512:
10930
            return "X25519MLKEM512";
10931
        #endif /* HAVE_CURVE25519 */
10932
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
10933
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
10934
0
    #ifndef WOLFSSL_NO_ML_KEM_768
10935
0
        case WOLFSSL_ML_KEM_768:
10936
0
            return "ML_KEM_768";
10937
0
        #ifdef WOLFSSL_PQC_HYBRIDS
10938
0
        case WOLFSSL_SECP256R1MLKEM768:
10939
0
            return "SecP256r1MLKEM768";
10940
0
        #ifdef HAVE_CURVE25519
10941
0
        case WOLFSSL_X25519MLKEM768:
10942
0
            return "X25519MLKEM768";
10943
0
        #endif
10944
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
10945
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
10946
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
10947
        case WOLFSSL_P384_ML_KEM_768_OLD:
10948
            return "P384_ML_KEM_768_OLD";
10949
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
10950
        case WOLFSSL_SECP384R1MLKEM768:
10951
            return "SecP384r1MLKEM768";
10952
        #ifdef HAVE_CURVE448
10953
        case WOLFSSL_X448MLKEM768:
10954
            return "X448MLKEM768";
10955
        #endif /* HAVE_CURVE448 */
10956
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
10957
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
10958
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
10959
0
        case WOLFSSL_ML_KEM_1024:
10960
0
            return "ML_KEM_1024";
10961
0
        #ifdef WOLFSSL_PQC_HYBRIDS
10962
0
        case WOLFSSL_SECP384R1MLKEM1024:
10963
0
            return "SecP384r1MLKEM1024";
10964
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
10965
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
10966
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
10967
        case WOLFSSL_P521_ML_KEM_1024_OLD:
10968
            return "P521_ML_KEM_1024_OLD";
10969
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
10970
        case WOLFSSL_SECP521R1MLKEM1024:
10971
            return "SecP521r1MLKEM1024";
10972
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
10973
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
10974
#elif defined(HAVE_LIBOQS)
10975
        case WOLFSSL_ML_KEM_512:
10976
            return "ML_KEM_512";
10977
        case WOLFSSL_ML_KEM_768:
10978
            return "ML_KEM_768";
10979
        case WOLFSSL_ML_KEM_1024:
10980
            return "ML_KEM_1024";
10981
        case WOLFSSL_SECP256R1MLKEM512:
10982
            return "SecP256r1MLKEM512";
10983
        case WOLFSSL_SECP384R1MLKEM768:
10984
            return "SecP384r1MLKEM768";
10985
        case WOLFSSL_SECP256R1MLKEM768:
10986
            return "SecP256r1MLKEM768";
10987
        case WOLFSSL_SECP521R1MLKEM1024:
10988
            return "SecP521r1MLKEM1024";
10989
        case WOLFSSL_SECP384R1MLKEM1024:
10990
            return "SecP384r1MLKEM1024";
10991
    #ifdef HAVE_CURVE25519
10992
        case WOLFSSL_X25519MLKEM512:
10993
            return "X25519MLKEM512";
10994
        case WOLFSSL_X25519MLKEM768:
10995
            return "X25519MLKEM768";
10996
    #endif
10997
    #ifdef HAVE_CURVE448
10998
        case WOLFSSL_X448MLKEM768:
10999
            return "X448MLKEM768";
11000
    #endif
11001
#endif /* WOLFSSL_WC_MLKEM */
11002
0
#endif /* WOLFSSL_NO_ML_KEM */
11003
#ifdef WOLFSSL_MLKEM_KYBER
11004
#if defined(WOLFSSL_WC_MLKEM)
11005
    #ifndef WOLFSSL_NO_KYBER512
11006
        case WOLFSSL_KYBER_LEVEL1:
11007
            return "KYBER_LEVEL1";
11008
        case WOLFSSL_P256_KYBER_LEVEL1:
11009
            return "P256_KYBER_LEVEL1";
11010
        #ifdef HAVE_CURVE25519
11011
        case WOLFSSL_X25519_KYBER_LEVEL1:
11012
            return "X25519_KYBER_LEVEL1";
11013
        #endif
11014
    #endif
11015
    #ifndef WOLFSSL_NO_KYBER768
11016
        case WOLFSSL_KYBER_LEVEL3:
11017
            return "KYBER_LEVEL3";
11018
        case WOLFSSL_P384_KYBER_LEVEL3:
11019
            return "P384_KYBER_LEVEL3";
11020
        case WOLFSSL_P256_KYBER_LEVEL3:
11021
            return "P256_KYBER_LEVEL3";
11022
        #ifdef HAVE_CURVE25519
11023
        case WOLFSSL_X25519_KYBER_LEVEL3:
11024
            return "X25519_KYBER_LEVEL3";
11025
        #endif
11026
        #ifdef HAVE_CURVE448
11027
        case WOLFSSL_X448_KYBER_LEVEL3:
11028
            return "X448_KYBER_LEVEL3";
11029
        #endif
11030
    #endif
11031
    #ifndef WOLFSSL_NO_KYBER1024
11032
        case WOLFSSL_KYBER_LEVEL5:
11033
            return "KYBER_LEVEL5";
11034
        case WOLFSSL_P521_KYBER_LEVEL5:
11035
            return "P521_KYBER_LEVEL5";
11036
    #endif
11037
#elif defined (HAVE_LIBOQS)
11038
        case WOLFSSL_KYBER_LEVEL1:
11039
            return "KYBER_LEVEL1";
11040
        case WOLFSSL_KYBER_LEVEL3:
11041
            return "KYBER_LEVEL3";
11042
        case WOLFSSL_KYBER_LEVEL5:
11043
            return "KYBER_LEVEL5";
11044
        case WOLFSSL_P256_KYBER_LEVEL1:
11045
            return "P256_KYBER_LEVEL1";
11046
        case WOLFSSL_P384_KYBER_LEVEL3:
11047
            return "P384_KYBER_LEVEL3";
11048
        case WOLFSSL_P256_KYBER_LEVEL3:
11049
            return "P256_KYBER_LEVEL3";
11050
        case WOLFSSL_P521_KYBER_LEVEL5:
11051
            return "P521_KYBER_LEVEL5";
11052
    #ifdef HAVE_CURVE25519
11053
        case WOLFSSL_X25519_KYBER_LEVEL1:
11054
            return "X25519_KYBER_LEVEL1";
11055
        case WOLFSSL_X25519_KYBER_LEVEL3:
11056
            return "X25519_KYBER_LEVEL3";
11057
    #endif
11058
    #ifdef HAVE_CURVE448
11059
        case WOLFSSL_X448_KYBER_LEVEL3:
11060
            return "X448_KYBER_LEVEL3";
11061
    #endif
11062
#endif /* WOLFSSL_WC_MLKEM */
11063
#endif /* WOLFSSL_MLKEM_KYBER */
11064
0
        }
11065
0
    }
11066
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
11067
11068
0
#ifdef HAVE_FFDHE
11069
0
    if (ssl->namedGroup != 0) {
11070
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
11071
0
    }
11072
0
#endif
11073
11074
0
#ifdef HAVE_CURVE25519
11075
0
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
11076
0
        cName = "X25519";
11077
0
    }
11078
0
#endif
11079
11080
0
#ifdef HAVE_CURVE448
11081
0
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
11082
0
        cName = "X448";
11083
0
    }
11084
0
#endif
11085
11086
0
#ifdef HAVE_ECC
11087
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
11088
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
11089
0
                                NULL));
11090
0
    }
11091
0
#endif
11092
11093
0
    return cName;
11094
0
}
11095
#endif
11096
11097
#ifdef OPENSSL_EXTRA
11098
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
11099
/* return authentication NID corresponding to cipher suite
11100
 * @param cipher a pointer to WOLFSSL_CIPHER
11101
 * return NID if found, WC_NID_undef if not found
11102
 */
11103
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
11104
{
11105
    static const struct authnid {
11106
        const char* alg_name;
11107
        const int  nid;
11108
    } authnid_tbl[] = {
11109
        {"RSA",     WC_NID_auth_rsa},
11110
        {"PSK",     WC_NID_auth_psk},
11111
        {"SRP",     WC_NID_auth_srp},
11112
        {"ECDSA",   WC_NID_auth_ecdsa},
11113
        {"None",    WC_NID_auth_null},
11114
        {NULL,      WC_NID_undef}
11115
    };
11116
11117
    const char* authStr;
11118
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11119
11120
    if (GetCipherSegment(cipher, n) == NULL) {
11121
        WOLFSSL_MSG("no suitable cipher name found");
11122
        return WC_NID_undef;
11123
    }
11124
11125
    authStr = GetCipherAuthStr(n);
11126
11127
    if (authStr != NULL) {
11128
        const struct authnid* sa;
11129
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
11130
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
11131
                return sa->nid;
11132
            }
11133
        }
11134
    }
11135
11136
    return WC_NID_undef;
11137
}
11138
/* return cipher NID corresponding to cipher suite
11139
 * @param cipher a pointer to WOLFSSL_CIPHER
11140
 * return NID if found, WC_NID_undef if not found
11141
 */
11142
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
11143
{
11144
    static const struct ciphernid {
11145
        const char* alg_name;
11146
        const int  nid;
11147
    } ciphernid_tbl[] = {
11148
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
11149
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
11150
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
11151
        {"AES(128)",                WC_NID_aes_128_cbc},
11152
        {"AES(256)",                WC_NID_aes_256_cbc},
11153
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
11154
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
11155
        {"RC4",                     WC_NID_rc4},
11156
        {"3DES",                    WC_NID_des_ede3_cbc},
11157
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
11158
        {"None",                    WC_NID_undef},
11159
        {NULL,                      WC_NID_undef}
11160
    };
11161
11162
    const char* encStr;
11163
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11164
11165
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
11166
11167
    if (GetCipherSegment(cipher, n) == NULL) {
11168
        WOLFSSL_MSG("no suitable cipher name found");
11169
        return WC_NID_undef;
11170
    }
11171
11172
    encStr = GetCipherEncStr(n);
11173
11174
    if (encStr != NULL) {
11175
        const struct ciphernid* c;
11176
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
11177
            if (XSTRCMP(c->alg_name, encStr) == 0) {
11178
                return c->nid;
11179
            }
11180
        }
11181
    }
11182
11183
    return WC_NID_undef;
11184
}
11185
/* return digest NID corresponding to cipher suite
11186
 * @param cipher a pointer to WOLFSSL_CIPHER
11187
 * return NID if found, WC_NID_undef if not found
11188
 */
11189
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
11190
{
11191
    static const struct macnid {
11192
        const char* alg_name;
11193
        const int  nid;
11194
    } macnid_tbl[] = {
11195
        {"SHA1",    WC_NID_sha1},
11196
        {"SHA256",  WC_NID_sha256},
11197
        {"SHA384",  WC_NID_sha384},
11198
        {NULL,      WC_NID_undef}
11199
    };
11200
11201
    const char* name;
11202
    const char* macStr;
11203
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11204
    (void)name;
11205
11206
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
11207
11208
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
11209
        WOLFSSL_MSG("no suitable cipher name found");
11210
        return WC_NID_undef;
11211
    }
11212
11213
    /* in MD5 case, NID will be WC_NID_md5 */
11214
    if (XSTRSTR(name, "MD5") != NULL) {
11215
        return WC_NID_md5;
11216
    }
11217
11218
    macStr = GetCipherMacStr(n);
11219
11220
    if (macStr != NULL) {
11221
        const struct macnid* mc;
11222
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
11223
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
11224
                return mc->nid;
11225
            }
11226
        }
11227
    }
11228
11229
    return WC_NID_undef;
11230
}
11231
/* return key exchange NID corresponding to cipher suite
11232
 * @param cipher a pointer to WOLFSSL_CIPHER
11233
 * return NID if found, WC_NID_undef if not found
11234
 */
11235
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
11236
{
11237
    static const struct kxnid {
11238
        const char* name;
11239
        const int  nid;
11240
    } kxnid_table[] = {
11241
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
11242
        {"ECDH",      WC_NID_kx_ecdhe},
11243
        {"DHEPSK",    WC_NID_kx_dhe_psk},
11244
        {"DH",        WC_NID_kx_dhe},
11245
        {"RSAPSK",    WC_NID_kx_rsa_psk},
11246
        {"SRP",       WC_NID_kx_srp},
11247
        {"EDH",       WC_NID_kx_dhe},
11248
        {"RSA",       WC_NID_kx_rsa},
11249
        {NULL,        WC_NID_undef}
11250
    };
11251
11252
    const char* keaStr;
11253
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11254
11255
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
11256
11257
    if (GetCipherSegment(cipher, n) == NULL) {
11258
        WOLFSSL_MSG("no suitable cipher name found");
11259
        return WC_NID_undef;
11260
    }
11261
11262
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
11263
    if (XSTRCMP(n[0], "TLS13") == 0) {
11264
        return WC_NID_kx_any;
11265
    }
11266
11267
    keaStr = GetCipherKeaStr(n);
11268
11269
    if (keaStr != NULL) {
11270
        const struct kxnid* k;
11271
        for(k = kxnid_table; k->name != NULL; k++) {
11272
            if (XSTRCMP(k->name, keaStr) == 0) {
11273
                return k->nid;
11274
            }
11275
        }
11276
    }
11277
11278
    return WC_NID_undef;
11279
}
11280
/* check if cipher suite is AEAD
11281
 * @param cipher a pointer to WOLFSSL_CIPHER
11282
 * return 1 if cipher is AEAD, 0 otherwise
11283
 */
11284
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
11285
{
11286
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11287
11288
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
11289
11290
    if (GetCipherSegment(cipher, n) == NULL) {
11291
        WOLFSSL_MSG("no suitable cipher name found");
11292
        return WC_NID_undef;
11293
    }
11294
11295
    return IsCipherAEAD(n);
11296
}
11297
/* Creates cipher->description based on cipher->offset
11298
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
11299
 * to a stack of ciphers.
11300
 * @param [in] cipher: A cipher from a stack of ciphers.
11301
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
11302
 */
11303
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
11304
{
11305
    int strLen;
11306
    unsigned long offset;
11307
    char* dp;
11308
    const char* name;
11309
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
11310
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
11311
    int len = MAX_DESCRIPTION_SZ-1;
11312
    const CipherSuiteInfo* cipher_names;
11313
    ProtocolVersion pv;
11314
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
11315
11316
    if (cipher == NULL)
11317
        return WOLFSSL_FAILURE;
11318
11319
    dp = cipher->description;
11320
    if (dp == NULL)
11321
        return WOLFSSL_FAILURE;
11322
11323
    cipher_names = GetCipherNames();
11324
11325
    offset = cipher->offset;
11326
    if (offset >= (unsigned long)GetCipherNamesSize())
11327
        return WOLFSSL_FAILURE;
11328
    pv.major = cipher_names[offset].major;
11329
    pv.minor = cipher_names[offset].minor;
11330
    protocol = wolfSSL_internal_get_version(&pv);
11331
11332
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
11333
        WOLFSSL_MSG("no suitable cipher name found");
11334
        return WOLFSSL_FAILURE;
11335
    }
11336
11337
    /* keaStr */
11338
    keaStr = GetCipherKeaStr(n);
11339
    /* authStr */
11340
    authStr = GetCipherAuthStr(n);
11341
    /* encStr */
11342
    encStr = GetCipherEncStr(n);
11343
    if ((cipher->bits = SetCipherBits(encStr)) ==
11344
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
11345
    {
11346
       WOLFSSL_MSG("Cipher Bits Not Set.");
11347
    }
11348
    /* macStr */
11349
    macStr = GetCipherMacStr(n);
11350
11351
11352
    /* Build up the string by copying onto the end. */
11353
    XSTRNCPY(dp, name, (size_t)len);
11354
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11355
    len -= strLen; dp += strLen;
11356
11357
    XSTRNCPY(dp, " ", (size_t)len);
11358
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11359
    len -= strLen; dp += strLen;
11360
    XSTRNCPY(dp, protocol, (size_t)len);
11361
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11362
    len -= strLen; dp += strLen;
11363
11364
    XSTRNCPY(dp, " Kx=", (size_t)len);
11365
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11366
    len -= strLen; dp += strLen;
11367
    XSTRNCPY(dp, keaStr, (size_t)len);
11368
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11369
    len -= strLen; dp += strLen;
11370
11371
    XSTRNCPY(dp, " Au=", (size_t)len);
11372
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11373
    len -= strLen; dp += strLen;
11374
    XSTRNCPY(dp, authStr, (size_t)len);
11375
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11376
    len -= strLen; dp += strLen;
11377
11378
    XSTRNCPY(dp, " Enc=", (size_t)len);
11379
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11380
    len -= strLen; dp += strLen;
11381
    XSTRNCPY(dp, encStr, (size_t)len);
11382
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11383
    len -= strLen; dp += strLen;
11384
11385
    XSTRNCPY(dp, " Mac=", (size_t)len);
11386
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
11387
    len -= strLen; dp += (size_t)strLen;
11388
    XSTRNCPY(dp, macStr, (size_t)len);
11389
    dp[len-1] = '\0';
11390
11391
    return WOLFSSL_SUCCESS;
11392
}
11393
#endif /* OPENSSL_ALL || WOLFSSL_QT */
11394
11395
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
11396
{
11397
    const char* keaStr;
11398
11399
    switch (kea) {
11400
        case no_kea:
11401
            keaStr = "None";
11402
            break;
11403
#ifndef NO_RSA
11404
        case rsa_kea:
11405
            keaStr = "RSA";
11406
            break;
11407
#endif
11408
#ifndef NO_DH
11409
        case diffie_hellman_kea:
11410
            keaStr = "DHE";
11411
            break;
11412
#endif
11413
        case fortezza_kea:
11414
            keaStr = "FZ";
11415
            break;
11416
#ifndef NO_PSK
11417
        case psk_kea:
11418
            keaStr = "PSK";
11419
            break;
11420
    #ifndef NO_DH
11421
        case dhe_psk_kea:
11422
            keaStr = "DHEPSK";
11423
            break;
11424
    #endif
11425
    #ifdef HAVE_ECC
11426
        case ecdhe_psk_kea:
11427
            keaStr = "ECDHEPSK";
11428
            break;
11429
    #endif
11430
#endif
11431
#ifdef HAVE_ECC
11432
        case ecc_diffie_hellman_kea:
11433
            keaStr = "ECDHE";
11434
            break;
11435
        case ecc_static_diffie_hellman_kea:
11436
            keaStr = "ECDH";
11437
            break;
11438
#endif
11439
        case any_kea:
11440
            keaStr = "any";
11441
            break;
11442
        default:
11443
            keaStr = "unknown";
11444
            break;
11445
    }
11446
11447
    return keaStr;
11448
}
11449
11450
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
11451
{
11452
    const char* authStr;
11453
11454
    switch (sig_algo) {
11455
        case anonymous_sa_algo:
11456
            authStr = "None";
11457
            break;
11458
#ifndef NO_RSA
11459
        case rsa_sa_algo:
11460
            authStr = "RSA";
11461
            break;
11462
    #ifdef WC_RSA_PSS
11463
        case rsa_pss_sa_algo:
11464
            authStr = "RSA-PSS";
11465
            break;
11466
    #endif
11467
#endif
11468
#ifndef NO_DSA
11469
        case dsa_sa_algo:
11470
            authStr = "DSA";
11471
            break;
11472
#endif
11473
#ifdef HAVE_ECC
11474
        case ecc_dsa_sa_algo:
11475
            authStr = "ECDSA";
11476
            break;
11477
#endif
11478
#ifdef WOLFSSL_SM2
11479
        case sm2_sa_algo:
11480
            authStr = "SM2";
11481
            break;
11482
#endif
11483
#ifdef HAVE_ED25519
11484
        case ed25519_sa_algo:
11485
            authStr = "Ed25519";
11486
            break;
11487
#endif
11488
#ifdef HAVE_ED448
11489
        case ed448_sa_algo:
11490
            authStr = "Ed448";
11491
            break;
11492
#endif
11493
        case any_sa_algo:
11494
            authStr = "any";
11495
            break;
11496
        default:
11497
            authStr = "unknown";
11498
            break;
11499
    }
11500
11501
    return authStr;
11502
}
11503
11504
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
11505
{
11506
    const char* encStr;
11507
11508
    (void)key_size;
11509
11510
    switch (cipher) {
11511
        case wolfssl_cipher_null:
11512
            encStr = "None";
11513
            break;
11514
#ifndef NO_RC4
11515
        case wolfssl_rc4:
11516
            encStr = "RC4(128)";
11517
            break;
11518
#endif
11519
#ifndef NO_DES3
11520
        case wolfssl_triple_des:
11521
            encStr = "3DES(168)";
11522
            break;
11523
#endif
11524
#ifndef NO_AES
11525
        case wolfssl_aes:
11526
            if (key_size == AES_128_KEY_SIZE)
11527
                encStr = "AES(128)";
11528
            else if (key_size == AES_256_KEY_SIZE)
11529
                encStr = "AES(256)";
11530
            else
11531
                encStr = "AES(?)";
11532
            break;
11533
    #ifdef HAVE_AESGCM
11534
        case wolfssl_aes_gcm:
11535
            if (key_size == AES_128_KEY_SIZE)
11536
                encStr = "AESGCM(128)";
11537
            else if (key_size == AES_256_KEY_SIZE)
11538
                encStr = "AESGCM(256)";
11539
            else
11540
                encStr = "AESGCM(?)";
11541
            break;
11542
    #endif
11543
    #ifdef HAVE_AESCCM
11544
        case wolfssl_aes_ccm:
11545
            if (key_size == AES_128_KEY_SIZE)
11546
                encStr = "AESCCM(128)";
11547
            else if (key_size == AES_256_KEY_SIZE)
11548
                encStr = "AESCCM(256)";
11549
            else
11550
                encStr = "AESCCM(?)";
11551
            break;
11552
    #endif
11553
#endif
11554
#ifdef HAVE_CHACHA
11555
        case wolfssl_chacha:
11556
            encStr = "CHACHA20/POLY1305(256)";
11557
            break;
11558
#endif
11559
#ifdef HAVE_ARIA
11560
        case wolfssl_aria_gcm:
11561
            if (key_size == ARIA_128_KEY_SIZE)
11562
                encStr = "Aria(128)";
11563
            else if (key_size == ARIA_192_KEY_SIZE)
11564
                encStr = "Aria(192)";
11565
            else if (key_size == ARIA_256_KEY_SIZE)
11566
                encStr = "Aria(256)";
11567
            else
11568
                encStr = "Aria(?)";
11569
            break;
11570
#endif
11571
#ifdef HAVE_CAMELLIA
11572
        case wolfssl_camellia:
11573
            if (key_size == CAMELLIA_128_KEY_SIZE)
11574
                encStr = "Camellia(128)";
11575
            else if (key_size == CAMELLIA_256_KEY_SIZE)
11576
                encStr = "Camellia(256)";
11577
            else
11578
                encStr = "Camellia(?)";
11579
            break;
11580
#endif
11581
        default:
11582
            encStr = "unknown";
11583
            break;
11584
    }
11585
11586
    return encStr;
11587
}
11588
11589
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
11590
{
11591
    const char* macStr;
11592
11593
    switch (mac) {
11594
        case no_mac:
11595
            macStr = "None";
11596
            break;
11597
#ifndef NO_MD5
11598
        case md5_mac:
11599
            macStr = "MD5";
11600
            break;
11601
#endif
11602
#ifndef NO_SHA
11603
        case sha_mac:
11604
            macStr = "SHA1";
11605
            break;
11606
#endif
11607
#ifdef WOLFSSL_SHA224
11608
        case sha224_mac:
11609
            macStr = "SHA224";
11610
            break;
11611
#endif
11612
#ifndef NO_SHA256
11613
        case sha256_mac:
11614
            macStr = "SHA256";
11615
            break;
11616
#endif
11617
#ifdef WOLFSSL_SHA384
11618
        case sha384_mac:
11619
            macStr = "SHA384";
11620
            break;
11621
#endif
11622
#ifdef WOLFSSL_SHA512
11623
        case sha512_mac:
11624
            macStr = "SHA512";
11625
            break;
11626
#endif
11627
        default:
11628
            macStr = "unknown";
11629
            break;
11630
    }
11631
11632
    return macStr;
11633
}
11634
11635
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
11636
                                 int len)
11637
{
11638
    char *ret = in;
11639
    const char *keaStr, *authStr, *encStr, *macStr;
11640
    size_t strLen;
11641
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
11642
11643
    if (cipher == NULL || in == NULL)
11644
        return NULL;
11645
11646
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
11647
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
11648
     * Return the description based on cipher_names[cipher->offset]
11649
     */
11650
    if (cipher->in_stack == TRUE) {
11651
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
11652
        XSTRNCPY(in,cipher->description,(size_t)len);
11653
        return ret;
11654
    }
11655
#endif
11656
11657
    /* Get the cipher description based on the SSL session cipher */
11658
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
11659
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
11660
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
11661
                                      cipher->ssl->specs.key_size);
11662
    if (cipher->ssl->specs.cipher_type == aead)
11663
        macStr = "AEAD";
11664
    else
11665
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
11666
11667
    /* Build up the string by copying onto the end. */
11668
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
11669
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11670
11671
    XSTRNCPY(in, " ", (size_t)len);
11672
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11673
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
11674
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11675
11676
    XSTRNCPY(in, " Kx=", (size_t)len);
11677
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11678
    XSTRNCPY(in, keaStr, (size_t)len);
11679
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11680
11681
    XSTRNCPY(in, " Au=", (size_t)len);
11682
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11683
    XSTRNCPY(in, authStr, (size_t)len);
11684
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11685
11686
    XSTRNCPY(in, " Enc=", (size_t)len);
11687
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11688
    XSTRNCPY(in, encStr, (size_t)len);
11689
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11690
11691
    XSTRNCPY(in, " Mac=", (size_t)len);
11692
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
11693
    XSTRNCPY(in, macStr, (size_t)len);
11694
    in[len-1] = '\0';
11695
11696
    return ret;
11697
}
11698
11699
int wolfSSL_OCSP_parse_url(const char* url, char** host, char** port,
11700
        char** path, int* ssl)
11701
{
11702
    const char* u = url;
11703
    const char* upath; /* path in u */
11704
    const char* uport; /* port in u */
11705
    const char* hostEnd;
11706
11707
    WOLFSSL_ENTER("OCSP_parse_url");
11708
11709
    *host = NULL;
11710
    *port = NULL;
11711
    *path = NULL;
11712
    *ssl = 0;
11713
11714
    if (*(u++) != 'h') goto err;
11715
    if (*(u++) != 't') goto err;
11716
    if (*(u++) != 't') goto err;
11717
    if (*(u++) != 'p') goto err;
11718
    if (*u == 's') {
11719
        *ssl = 1;
11720
        u++;
11721
        *port = CopyString("443", -1, NULL, DYNAMIC_TYPE_OPENSSL);
11722
    }
11723
    else if (*u == ':') {
11724
        *ssl = 0;
11725
        *port = CopyString("80", -1, NULL, DYNAMIC_TYPE_OPENSSL);
11726
    }
11727
    else
11728
        goto err;
11729
    if (*port == NULL)
11730
        goto err;
11731
    if (*(u++) != ':') goto err;
11732
    if (*(u++) != '/') goto err;
11733
    if (*(u++) != '/') goto err;
11734
11735
    /* Look for path */
11736
    upath = XSTRSTR(u, "/");
11737
    *path = CopyString(upath == NULL ? "/" : upath, -1, NULL,
11738
                       DYNAMIC_TYPE_OPENSSL);
11739
11740
    /* Look for port */
11741
    uport = XSTRSTR(u, ":");
11742
    if (uport != NULL) {
11743
        if (*(++uport) == '\0')
11744
            goto err;
11745
        /* port must be before path */
11746
        if (upath != NULL && uport >= upath)
11747
            goto err;
11748
        XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
11749
        if (upath)
11750
            *port = CopyString(uport, (int)(upath - uport), NULL,
11751
                               DYNAMIC_TYPE_OPENSSL);
11752
        else
11753
            *port = CopyString(uport, -1, NULL, DYNAMIC_TYPE_OPENSSL);
11754
        if (*port == NULL)
11755
            goto err;
11756
        hostEnd = uport - 1;
11757
    }
11758
    else
11759
        hostEnd = upath;
11760
11761
    if (hostEnd)
11762
        *host = CopyString(u, (int)(hostEnd - u), NULL, DYNAMIC_TYPE_OPENSSL);
11763
    else
11764
        *host = CopyString(u, -1, NULL, DYNAMIC_TYPE_OPENSSL);
11765
11766
    if (*host == NULL)
11767
        goto err;
11768
11769
    return WOLFSSL_SUCCESS;
11770
err:
11771
    XFREE(*host, NULL, DYNAMIC_TYPE_OPENSSL);
11772
    *host = NULL;
11773
    XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
11774
    *port = NULL;
11775
    XFREE(*path, NULL, DYNAMIC_TYPE_OPENSSL);
11776
    *path = NULL;
11777
    return WOLFSSL_FAILURE;
11778
}
11779
11780
#ifndef NO_WOLFSSL_STUB
11781
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
11782
{
11783
    WOLFSSL_STUB("COMP_zlib");
11784
    return 0;
11785
}
11786
11787
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
11788
{
11789
    WOLFSSL_STUB("COMP_rle");
11790
    return 0;
11791
}
11792
11793
int wolfSSL_COMP_add_compression_method(int method, void* data)
11794
{
11795
    (void)method;
11796
    (void)data;
11797
    WOLFSSL_STUB("COMP_add_compression_method");
11798
    return 0;
11799
}
11800
11801
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
11802
    (void)ssl;
11803
    return NULL;
11804
}
11805
11806
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
11807
    (void)ssl;
11808
    return NULL;
11809
}
11810
11811
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
11812
{
11813
    static const char ret[] = "not supported";
11814
11815
    (void)comp;
11816
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
11817
    return ret;
11818
}
11819
#endif
11820
11821
/*  wolfSSL_set_dynlock_create_callback
11822
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
11823
 *  This function exists for compatibility purposes because wolfSSL satisfies
11824
 *  thread safety without relying on the callback.
11825
 */
11826
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
11827
                                                          const char*, int))
11828
{
11829
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
11830
    (void)f;
11831
}
11832
/*  wolfSSL_set_dynlock_lock_callback
11833
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
11834
 *  This function exists for compatibility purposes because wolfSSL satisfies
11835
 *  thread safety without relying on the callback.
11836
 */
11837
void wolfSSL_set_dynlock_lock_callback(
11838
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
11839
{
11840
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
11841
    (void)f;
11842
}
11843
/*  wolfSSL_set_dynlock_destroy_callback
11844
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
11845
 *  This function exists for compatibility purposes because wolfSSL satisfies
11846
 *  thread safety without relying on the callback.
11847
 */
11848
void wolfSSL_set_dynlock_destroy_callback(
11849
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
11850
{
11851
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
11852
    (void)f;
11853
}
11854
11855
/* Sets the DNS hostname to name.
11856
 * Hostname is cleared if name is NULL or empty. */
11857
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
11858
{
11859
    if (ssl == NULL) {
11860
        return WOLFSSL_FAILURE;
11861
    }
11862
11863
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
11864
}
11865
11866
/******************************************************************************
11867
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
11868
*
11869
* RETURNS:
11870
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
11871
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
11872
*   same as openssl.
11873
*/
11874
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
11875
{
11876
    if (ctx == NULL || vpm == NULL)
11877
        return WOLFSSL_SUCCESS;
11878
11879
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
11880
}
11881
11882
/******************************************************************************
11883
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
11884
*
11885
* RETURNS:
11886
* returns pointer to the SSL verification parameters on success,
11887
* otherwise returns NULL
11888
*/
11889
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
11890
{
11891
    if (ctx == NULL) {
11892
        return NULL;
11893
    }
11894
11895
    return ctx->param;
11896
}
11897
11898
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
11899
{
11900
    if (ssl == NULL) {
11901
        return NULL;
11902
    }
11903
    return ssl->param;
11904
}
11905
11906
#endif /* OPENSSL_EXTRA */
11907
11908
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
11909
/* Gets an index to store SSL structure at.
11910
 *
11911
 * Returns positive index on success and negative values on failure
11912
 */
11913
int wolfSSL_get_ex_data_X509_STORE_CTX_idx(void)
11914
{
11915
    WOLFSSL_ENTER("wolfSSL_get_ex_data_X509_STORE_CTX_idx");
11916
11917
    /* store SSL at index 0 */
11918
    return 0;
11919
}
11920
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
11921
11922
#ifdef OPENSSL_EXTRA
11923
/* Sets a function callback that will send information about the state of all
11924
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
11925
 * in.
11926
 *
11927
 * ctx WOLFSSL_CTX structure to set callback function in
11928
 * f   callback function to use
11929
 */
11930
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
11931
       void (*f)(const WOLFSSL* ssl, int type, int val))
11932
{
11933
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
11934
    if (ctx == NULL) {
11935
        WOLFSSL_MSG("Bad function argument");
11936
    }
11937
    else {
11938
        ctx->CBIS = f;
11939
    }
11940
}
11941
11942
void wolfSSL_set_info_callback(WOLFSSL* ssl,
11943
       void (*f)(const WOLFSSL* ssl, int type, int val))
11944
{
11945
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
11946
    if (ssl == NULL) {
11947
        WOLFSSL_MSG("Bad function argument");
11948
    }
11949
    else {
11950
        ssl->CBIS = f;
11951
    }
11952
}
11953
11954
11955
unsigned long wolfSSL_ERR_peek_error(void)
11956
{
11957
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error");
11958
11959
    return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL);
11960
}
11961
11962
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H
11963
#include <wolfssl/debug-untrace-error-codes.h>
11964
#endif
11965
11966
int wolfSSL_ERR_GET_LIB(unsigned long err)
11967
{
11968
    unsigned long value;
11969
11970
    value = (err & 0xFFFFFFL);
11971
    switch (value) {
11972
    case -PARSE_ERROR:
11973
        return WOLFSSL_ERR_LIB_SSL;
11974
    case -ASN_NO_PEM_HEADER:
11975
    case -WOLFSSL_PEM_R_NO_START_LINE_E:
11976
    case -WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E:
11977
    case -WOLFSSL_PEM_R_BAD_PASSWORD_READ_E:
11978
    case -WOLFSSL_PEM_R_BAD_DECRYPT_E:
11979
        return WOLFSSL_ERR_LIB_PEM;
11980
    case -WOLFSSL_EVP_R_BAD_DECRYPT_E:
11981
    case -WOLFSSL_EVP_R_BN_DECODE_ERROR:
11982
    case -WOLFSSL_EVP_R_DECODE_ERROR:
11983
    case -WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR:
11984
        return WOLFSSL_ERR_LIB_EVP;
11985
    case -WOLFSSL_ASN1_R_HEADER_TOO_LONG_E:
11986
        return WOLFSSL_ERR_LIB_ASN1;
11987
    default:
11988
        return 0;
11989
    }
11990
}
11991
11992
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES
11993
#include <wolfssl/debug-trace-error-codes.h>
11994
#endif
11995
11996
/* This function is to find global error values that are the same through out
11997
 * all library version. With wolfSSL having only one set of error codes the
11998
 * return value is pretty straight forward. The only thing needed is all wolfSSL
11999
 * error values are typically negative.
12000
 *
12001
 * Returns the error reason
12002
 */
12003
int wolfSSL_ERR_GET_REASON(unsigned long err)
12004
{
12005
    int ret = (int)err;
12006
12007
    WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON");
12008
12009
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
12010
    /* Nginx looks for this error to know to stop parsing certificates.
12011
     * Same for HAProxy. */
12012
    if ((err == (unsigned long)((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE)) ||
12013
        ((err & 0xFFFFFFL) == (unsigned long)(-WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))) ||
12014
        ((err & 0xFFFL) == (unsigned long)PEM_R_NO_START_LINE))
12015
        return PEM_R_NO_START_LINE;
12016
    if (err == (unsigned long)((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST))
12017
        return SSL_R_HTTP_REQUEST;
12018
#endif
12019
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
12020
    if (err == (unsigned long)((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG))
12021
        return ASN1_R_HEADER_TOO_LONG;
12022
#endif
12023
12024
    /* check if error value is in range of wolfCrypt or wolfSSL errors */
12025
    ret = 0 - ret; /* setting as negative value */
12026
12027
    if ((ret <= WC_SPAN1_FIRST_E && ret >= WC_SPAN1_LAST_E) ||
12028
        (ret <= WC_SPAN2_FIRST_E && ret >= WC_SPAN2_LAST_E) ||
12029
        (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E))
12030
    {
12031
        return ret;
12032
    }
12033
    else {
12034
        WOLFSSL_MSG("Not in range of typical error values");
12035
        ret = (int)err;
12036
    }
12037
12038
    return ret;
12039
}
12040
12041
#ifndef NO_TLS
12042
/* returns a string that describes the alert
12043
 *
12044
 * alertID the alert value to look up
12045
 */
12046
const char* wolfSSL_alert_type_string_long(int alertID)
12047
{
12048
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
12049
12050
    return AlertTypeToString(alertID);
12051
}
12052
12053
const char* wolfSSL_alert_desc_string_long(int alertID)
12054
{
12055
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
12056
12057
    return AlertTypeToString(alertID);
12058
}
12059
#endif /* !NO_TLS */
12060
12061
#define STATE_STRINGS_PROTO(s) \
12062
    {                          \
12063
        {"SSLv3 " s,           \
12064
         "SSLv3 " s,           \
12065
         "SSLv3 " s},          \
12066
        {"TLSv1 " s,           \
12067
         "TLSv1 " s,           \
12068
         "TLSv1 " s},          \
12069
        {"TLSv1_1 " s,         \
12070
         "TLSv1_1 " s,         \
12071
         "TLSv1_1 " s},        \
12072
        {"TLSv1_2 " s,         \
12073
         "TLSv1_2 " s,         \
12074
         "TLSv1_2 " s},        \
12075
        {"TLSv1_3 " s,         \
12076
         "TLSv1_3 " s,         \
12077
         "TLSv1_3 " s},        \
12078
        {"DTLSv1 " s,          \
12079
         "DTLSv1 " s,          \
12080
         "DTLSv1 " s},         \
12081
        {"DTLSv1_2 " s,        \
12082
         "DTLSv1_2 " s,        \
12083
         "DTLSv1_2 " s},       \
12084
        {"DTLSv1_3 " s,        \
12085
         "DTLSv1_3 " s,        \
12086
         "DTLSv1_3 " s},       \
12087
    }
12088
12089
#define STATE_STRINGS_PROTO_RW(s) \
12090
    {                             \
12091
        {"SSLv3 read " s,         \
12092
         "SSLv3 write " s,        \
12093
         "SSLv3 " s},             \
12094
        {"TLSv1 read " s,         \
12095
         "TLSv1 write " s,        \
12096
         "TLSv1 " s},             \
12097
        {"TLSv1_1 read " s,       \
12098
         "TLSv1_1 write " s,      \
12099
         "TLSv1_1 " s},           \
12100
        {"TLSv1_2 read " s,       \
12101
         "TLSv1_2 write " s,      \
12102
         "TLSv1_2 " s},           \
12103
        {"TLSv1_3 read " s,       \
12104
         "TLSv1_3 write " s,      \
12105
         "TLSv1_3 " s},           \
12106
        {"DTLSv1 read " s,        \
12107
         "DTLSv1 write " s,       \
12108
         "DTLSv1 " s},            \
12109
        {"DTLSv1_2 read " s,      \
12110
         "DTLSv1_2 write " s,     \
12111
         "DTLSv1_2 " s},          \
12112
        {"DTLSv1_3 read " s,      \
12113
         "DTLSv1_3 write " s,     \
12114
         "DTLSv1_3 " s},          \
12115
    }
12116
12117
/* Gets the current state of the WOLFSSL structure
12118
 *
12119
 * ssl WOLFSSL structure to get state of
12120
 *
12121
 * Returns a human readable string of the WOLFSSL structure state
12122
 */
12123
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
12124
{
12125
12126
    static const char* OUTPUT_STR[24][8][3] = {
12127
        STATE_STRINGS_PROTO("Initialization"),
12128
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
12129
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
12130
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
12131
        STATE_STRINGS_PROTO_RW("Server Hello"),
12132
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
12133
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
12134
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
12135
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
12136
        STATE_STRINGS_PROTO_RW("Server Cert"),
12137
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
12138
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
12139
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
12140
        STATE_STRINGS_PROTO_RW("Server Finished"),
12141
        STATE_STRINGS_PROTO_RW("server Key Update"),
12142
        STATE_STRINGS_PROTO_RW("Client Hello"),
12143
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
12144
        STATE_STRINGS_PROTO_RW("Client Cert"),
12145
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
12146
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
12147
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
12148
        STATE_STRINGS_PROTO_RW("Client Finished"),
12149
        STATE_STRINGS_PROTO_RW("Client Key Update"),
12150
        STATE_STRINGS_PROTO("Handshake Done"),
12151
    };
12152
    enum ProtocolVer {
12153
        SSL_V3 = 0,
12154
        TLS_V1,
12155
        TLS_V1_1,
12156
        TLS_V1_2,
12157
        TLS_V1_3,
12158
        DTLS_V1,
12159
        DTLS_V1_2,
12160
        DTLS_V1_3,
12161
        UNKNOWN = 100
12162
    };
12163
12164
    enum IOMode {
12165
        SS_READ = 0,
12166
        SS_WRITE,
12167
        SS_NEITHER
12168
    };
12169
12170
    enum SslState {
12171
        ss_null_state = 0,
12172
        ss_server_hellorequest,
12173
        ss_server_helloverify,
12174
        ss_server_helloretryrequest,
12175
        ss_server_hello,
12176
        ss_server_certificatestatus,
12177
        ss_server_encryptedextensions,
12178
        ss_server_sessionticket,
12179
        ss_server_certrequest,
12180
        ss_server_cert,
12181
        ss_server_keyexchange,
12182
        ss_server_hellodone,
12183
        ss_server_changecipherspec,
12184
        ss_server_finished,
12185
        ss_server_keyupdate,
12186
        ss_client_hello,
12187
        ss_client_keyexchange,
12188
        ss_client_cert,
12189
        ss_client_changecipherspec,
12190
        ss_client_certverify,
12191
        ss_client_endofearlydata,
12192
        ss_client_finished,
12193
        ss_client_keyupdate,
12194
        ss_handshake_done
12195
    };
12196
12197
    int protocol = 0;
12198
    int cbmode = 0;
12199
    int state = 0;
12200
12201
    WOLFSSL_ENTER("wolfSSL_state_string_long");
12202
    if (ssl == NULL) {
12203
        WOLFSSL_MSG("Null argument passed in");
12204
        return NULL;
12205
    }
12206
12207
    /* Get state of callback */
12208
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
12209
        cbmode =  SS_WRITE;
12210
    }
12211
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
12212
        cbmode =  SS_READ;
12213
    }
12214
    else {
12215
        cbmode =  SS_NEITHER;
12216
    }
12217
12218
    /* Get protocol version */
12219
    switch (ssl->version.major) {
12220
        case SSLv3_MAJOR:
12221
            switch (ssl->version.minor) {
12222
                case SSLv3_MINOR:
12223
                    protocol = SSL_V3;
12224
                    break;
12225
                case TLSv1_MINOR:
12226
                    protocol = TLS_V1;
12227
                    break;
12228
                case TLSv1_1_MINOR:
12229
                    protocol = TLS_V1_1;
12230
                    break;
12231
                case TLSv1_2_MINOR:
12232
                    protocol = TLS_V1_2;
12233
                    break;
12234
                case TLSv1_3_MINOR:
12235
                    protocol = TLS_V1_3;
12236
                    break;
12237
                default:
12238
                    protocol = UNKNOWN;
12239
            }
12240
            break;
12241
        case DTLS_MAJOR:
12242
            switch (ssl->version.minor) {
12243
                case DTLS_MINOR:
12244
                    protocol = DTLS_V1;
12245
                    break;
12246
                case DTLSv1_2_MINOR:
12247
                    protocol = DTLS_V1_2;
12248
                    break;
12249
                case DTLSv1_3_MINOR:
12250
                    protocol = DTLS_V1_3;
12251
                    break;
12252
                default:
12253
                    protocol = UNKNOWN;
12254
            }
12255
            break;
12256
    default:
12257
        protocol = UNKNOWN;
12258
    }
12259
12260
    /* accept process */
12261
    if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
12262
        state = ssl->cbtype;
12263
        switch (state) {
12264
            case hello_request:
12265
                state = ss_server_hellorequest;
12266
                break;
12267
            case client_hello:
12268
                state = ss_client_hello;
12269
                break;
12270
            case server_hello:
12271
                state = ss_server_hello;
12272
                break;
12273
            case hello_verify_request:
12274
                state = ss_server_helloverify;
12275
                break;
12276
            case session_ticket:
12277
                state = ss_server_sessionticket;
12278
                break;
12279
            case end_of_early_data:
12280
                state = ss_client_endofearlydata;
12281
                break;
12282
            case hello_retry_request:
12283
                state = ss_server_helloretryrequest;
12284
                break;
12285
            case encrypted_extensions:
12286
                state = ss_server_encryptedextensions;
12287
                break;
12288
            case certificate:
12289
                if (ssl->options.side == WOLFSSL_SERVER_END)
12290
                    state = ss_client_cert;
12291
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
12292
                    state = ss_server_cert;
12293
                else {
12294
                    WOLFSSL_MSG("Unknown State");
12295
                    state = ss_null_state;
12296
                }
12297
                break;
12298
            case server_key_exchange:
12299
                state = ss_server_keyexchange;
12300
                break;
12301
            case certificate_request:
12302
                state = ss_server_certrequest;
12303
                break;
12304
            case server_hello_done:
12305
                state = ss_server_hellodone;
12306
                break;
12307
            case certificate_verify:
12308
                state = ss_client_certverify;
12309
                break;
12310
            case client_key_exchange:
12311
                state = ss_client_keyexchange;
12312
                break;
12313
            case finished:
12314
                if (ssl->options.side == WOLFSSL_SERVER_END)
12315
                    state = ss_client_finished;
12316
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
12317
                    state = ss_server_finished;
12318
                else {
12319
                    WOLFSSL_MSG("Unknown State");
12320
                    state = ss_null_state;
12321
                }
12322
                break;
12323
            case certificate_status:
12324
                state = ss_server_certificatestatus;
12325
                break;
12326
            case key_update:
12327
                if (ssl->options.side == WOLFSSL_SERVER_END)
12328
                    state = ss_client_keyupdate;
12329
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
12330
                    state = ss_server_keyupdate;
12331
                else {
12332
                    WOLFSSL_MSG("Unknown State");
12333
                    state = ss_null_state;
12334
                }
12335
                break;
12336
            case change_cipher_hs:
12337
                if (ssl->options.side == WOLFSSL_SERVER_END)
12338
                    state = ss_client_changecipherspec;
12339
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
12340
                    state = ss_server_changecipherspec;
12341
                else {
12342
                    WOLFSSL_MSG("Unknown State");
12343
                    state = ss_null_state;
12344
                }
12345
                break;
12346
            default:
12347
                WOLFSSL_MSG("Unknown State");
12348
                state = ss_null_state;
12349
        }
12350
    }
12351
    else {
12352
        /* Send process */
12353
        if (ssl->options.side == WOLFSSL_SERVER_END)
12354
            state = ssl->options.serverState;
12355
        else
12356
            state = ssl->options.clientState;
12357
12358
        switch (state) {
12359
            case SERVER_HELLOVERIFYREQUEST_COMPLETE:
12360
                state = ss_server_helloverify;
12361
                break;
12362
            case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
12363
                state = ss_server_helloretryrequest;
12364
                break;
12365
            case SERVER_HELLO_COMPLETE:
12366
                state = ss_server_hello;
12367
                break;
12368
            case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
12369
                state = ss_server_encryptedextensions;
12370
                break;
12371
            case SERVER_CERT_COMPLETE:
12372
                state = ss_server_cert;
12373
                break;
12374
            case SERVER_KEYEXCHANGE_COMPLETE:
12375
                state = ss_server_keyexchange;
12376
                break;
12377
            case SERVER_HELLODONE_COMPLETE:
12378
                state = ss_server_hellodone;
12379
                break;
12380
            case SERVER_CHANGECIPHERSPEC_COMPLETE:
12381
                state = ss_server_changecipherspec;
12382
                break;
12383
            case SERVER_FINISHED_COMPLETE:
12384
                state = ss_server_finished;
12385
                break;
12386
            case CLIENT_HELLO_RETRY:
12387
            case CLIENT_HELLO_COMPLETE:
12388
                state = ss_client_hello;
12389
                break;
12390
            case CLIENT_KEYEXCHANGE_COMPLETE:
12391
                state = ss_client_keyexchange;
12392
                break;
12393
            case CLIENT_CHANGECIPHERSPEC_COMPLETE:
12394
                state = ss_client_changecipherspec;
12395
                break;
12396
            case CLIENT_FINISHED_COMPLETE:
12397
                state = ss_client_finished;
12398
                break;
12399
            case HANDSHAKE_DONE:
12400
                state = ss_handshake_done;
12401
                break;
12402
            default:
12403
                WOLFSSL_MSG("Unknown State");
12404
                state = ss_null_state;
12405
        }
12406
    }
12407
12408
    if (protocol == UNKNOWN) {
12409
        WOLFSSL_MSG("Unknown protocol");
12410
        return "";
12411
    }
12412
    else {
12413
        return OUTPUT_STR[state][protocol][cbmode];
12414
    }
12415
}
12416
12417
#endif /* OPENSSL_EXTRA */
12418
12419
static long wolf_set_options(long old_op, long op)
12420
0
{
12421
    /* if SSL_OP_ALL then turn all bug workarounds on */
12422
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
12423
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
12424
0
    }
12425
12426
    /* by default cookie exchange is on with DTLS */
12427
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
12428
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
12429
0
    }
12430
12431
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
12432
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
12433
0
    }
12434
12435
#ifdef SSL_OP_NO_TLSv1_3
12436
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
12437
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
12438
    }
12439
#endif
12440
12441
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
12442
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
12443
0
    }
12444
12445
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
12446
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
12447
0
    }
12448
12449
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
12450
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
12451
0
    }
12452
12453
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
12454
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
12455
0
    }
12456
12457
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
12458
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
12459
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
12460
0
    }
12461
12462
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
12463
    #ifdef HAVE_LIBZ
12464
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
12465
    #else
12466
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
12467
0
    #endif
12468
0
    }
12469
12470
0
    return old_op | op;
12471
0
}
12472
12473
static int FindHashSig(const Suites* suites, byte first, byte second)
12474
0
{
12475
0
    word16 i;
12476
12477
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
12478
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
12479
0
        return SUITES_ERROR;
12480
0
    }
12481
12482
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
12483
0
        if (suites->hashSigAlgo[i]   == first &&
12484
0
            suites->hashSigAlgo[i+1] == second )
12485
0
            return i;
12486
0
    }
12487
12488
0
    return MATCH_SUITE_ERROR;
12489
0
}
12490
12491
long wolfSSL_set_options(WOLFSSL* ssl, long op)
12492
0
{
12493
0
    word16 haveRSA = 1;
12494
0
    word16 havePSK = 0;
12495
0
    int    keySz   = 0;
12496
12497
0
    WOLFSSL_ENTER("wolfSSL_set_options");
12498
12499
0
    if (ssl == NULL) {
12500
0
        return 0;
12501
0
    }
12502
12503
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
12504
12505
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
12506
0
        WOLFSSL_MSG("Disabling TLS 1.3");
12507
0
        if (ssl->version.minor == TLSv1_3_MINOR)
12508
0
            ssl->version.minor = TLSv1_2_MINOR;
12509
0
    }
12510
12511
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
12512
0
        WOLFSSL_MSG("Disabling TLS 1.2");
12513
0
        if (ssl->version.minor == TLSv1_2_MINOR)
12514
0
            ssl->version.minor = TLSv1_1_MINOR;
12515
0
    }
12516
12517
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
12518
0
        WOLFSSL_MSG("Disabling TLS 1.1");
12519
0
        if (ssl->version.minor == TLSv1_1_MINOR)
12520
0
            ssl->version.minor = TLSv1_MINOR;
12521
0
    }
12522
12523
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
12524
0
        WOLFSSL_MSG("Disabling TLS 1.0");
12525
0
        if (ssl->version.minor == TLSv1_MINOR)
12526
0
            ssl->version.minor = SSLv3_MINOR;
12527
0
    }
12528
12529
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
12530
0
        == WOLFSSL_OP_NO_COMPRESSION) {
12531
    #ifdef HAVE_LIBZ
12532
        ssl->options.usingCompression = 0;
12533
    #endif
12534
0
    }
12535
12536
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
12537
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
12538
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
12539
      ssl->options.noTicketTls12 = 1;
12540
    }
12541
#endif
12542
12543
12544
    /* in the case of a version change the cipher suites should be reset */
12545
#ifndef NO_PSK
12546
    havePSK = ssl->options.havePSK;
12547
#endif
12548
#ifdef NO_RSA
12549
    haveRSA = 0;
12550
#endif
12551
0
#ifndef NO_CERTS
12552
0
    keySz = ssl->buffers.keySz;
12553
0
#endif
12554
12555
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
12556
0
        if (AllocateSuites(ssl) != 0)
12557
0
            return 0;
12558
0
        if (!ssl->suites->setSuites) {
12559
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
12560
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
12561
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
12562
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
12563
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
12564
0
                       ssl->options.useAnon,
12565
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
12566
0
            else
12567
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
12568
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
12569
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
12570
0
                       ssl->options.useAnon,
12571
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
12572
0
        }
12573
0
        else {
12574
            /* Only preserve overlapping suites */
12575
0
            Suites tmpSuites;
12576
0
            word16 in, out;
12577
0
            word16 haveECDSAsig, haveStaticECC;
12578
#ifdef NO_RSA
12579
            haveECDSAsig = 1;
12580
            haveStaticECC = 1;
12581
#else
12582
0
            haveECDSAsig = 0;
12583
0
            haveStaticECC = ssl->options.haveStaticECC;
12584
0
#endif
12585
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
12586
            /* Get all possible ciphers and sigalgs for the version. Following
12587
             * options limit the allowed ciphers so let's try to get as many as
12588
             * possible.
12589
             * - haveStaticECC turns off haveRSA
12590
             * - haveECDSAsig turns off haveRSAsig */
12591
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
12592
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
12593
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
12594
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
12595
0
                        ssl->suites->suites[in+1]) >= 0) {
12596
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
12597
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
12598
0
                    out += SUITE_LEN;
12599
0
                }
12600
0
            }
12601
0
            ssl->suites->suiteSz = out;
12602
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
12603
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
12604
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
12605
0
                    ssl->suites->hashSigAlgo[out] =
12606
0
                            ssl->suites->hashSigAlgo[in];
12607
0
                    ssl->suites->hashSigAlgo[out+1] =
12608
0
                            ssl->suites->hashSigAlgo[in+1];
12609
0
                    out += 2;
12610
0
                }
12611
0
            }
12612
0
            ssl->suites->hashSigAlgoSz = out;
12613
0
        }
12614
0
    }
12615
12616
0
    return (long)ssl->options.mask;
12617
0
}
12618
12619
12620
long wolfSSL_get_options(const WOLFSSL* ssl)
12621
61.1k
{
12622
61.1k
    WOLFSSL_ENTER("wolfSSL_get_options");
12623
61.1k
    if(ssl == NULL)
12624
0
        return WOLFSSL_FAILURE;
12625
61.1k
    return (long)ssl->options.mask;
12626
61.1k
}
12627
12628
#if defined(HAVE_SECURE_RENEGOTIATION) \
12629
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
12630
/* clears the counter for number of renegotiations done
12631
 * returns the current count before it is cleared */
12632
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
12633
0
{
12634
0
    long total;
12635
12636
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
12637
0
    if (s == NULL)
12638
0
        return 0;
12639
12640
0
    total = s->secure_rene_count;
12641
0
    s->secure_rene_count = 0;
12642
0
    return total;
12643
0
}
12644
12645
12646
/* return the number of renegotiations since wolfSSL_new */
12647
long wolfSSL_total_renegotiations(WOLFSSL *s)
12648
0
{
12649
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
12650
0
    return wolfSSL_num_renegotiations(s);
12651
0
}
12652
12653
12654
/* return the number of renegotiations since wolfSSL_new */
12655
long wolfSSL_num_renegotiations(WOLFSSL* s)
12656
0
{
12657
0
    if (s == NULL) {
12658
0
        return 0;
12659
0
    }
12660
12661
0
    return s->secure_rene_count;
12662
0
}
12663
12664
12665
/* Is there a renegotiation currently in progress? */
12666
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
12667
0
{
12668
0
    return s && s->options.handShakeDone &&
12669
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
12670
0
}
12671
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
12672
12673
#ifdef OPENSSL_EXTRA
12674
12675
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
12676
{
12677
    WOLFSSL_ENTER("wolfSSL_clear_options");
12678
    if(ssl == NULL)
12679
        return WOLFSSL_FAILURE;
12680
    ssl->options.mask &= (unsigned long)~opt;
12681
    return (long)ssl->options.mask;
12682
}
12683
12684
#ifdef HAVE_PK_CALLBACKS
12685
long wolfSSL_set_tlsext_debug_arg(WOLFSSL* ssl, void *arg)
12686
{
12687
    if (ssl == NULL) {
12688
        return WOLFSSL_FAILURE;
12689
    }
12690
12691
    ssl->loggingCtx = arg;
12692
    return WOLFSSL_SUCCESS;
12693
}
12694
#endif /* HAVE_PK_CALLBACKS */
12695
12696
#ifndef NO_WOLFSSL_STUB
12697
long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg)
12698
{
12699
    (void)s;
12700
    (void)arg;
12701
    WOLFSSL_STUB("wolfSSL_get_tlsext_status_exts");
12702
    return WOLFSSL_FAILURE;
12703
}
12704
#endif
12705
12706
/*** TBD ***/
12707
#ifndef NO_WOLFSSL_STUB
12708
long wolfSSL_set_tlsext_status_exts(WOLFSSL *s, void *arg)
12709
{
12710
    (void)s;
12711
    (void)arg;
12712
    WOLFSSL_STUB("wolfSSL_set_tlsext_status_exts");
12713
    return WOLFSSL_FAILURE;
12714
}
12715
#endif
12716
12717
/*** TBD ***/
12718
#ifndef NO_WOLFSSL_STUB
12719
long wolfSSL_get_tlsext_status_ids(WOLFSSL *s, void *arg)
12720
{
12721
    (void)s;
12722
    (void)arg;
12723
    WOLFSSL_STUB("wolfSSL_get_tlsext_status_ids");
12724
    return WOLFSSL_FAILURE;
12725
}
12726
#endif
12727
12728
/*** TBD ***/
12729
#ifndef NO_WOLFSSL_STUB
12730
long wolfSSL_set_tlsext_status_ids(WOLFSSL *s, void *arg)
12731
{
12732
    (void)s;
12733
    (void)arg;
12734
    WOLFSSL_STUB("wolfSSL_set_tlsext_status_ids");
12735
    return WOLFSSL_FAILURE;
12736
}
12737
#endif
12738
12739
#ifndef NO_WOLFSSL_STUB
12740
/*** TBD ***/
12741
WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl)
12742
{
12743
    (void)ssl;
12744
    WOLFSSL_STUB("SSL_get_privatekey");
12745
    return NULL;
12746
}
12747
#endif
12748
12749
#ifndef NO_WOLFSSL_STUB
12750
/*** TBD ***/
12751
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
12752
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
12753
{
12754
    (void)ctx;
12755
    (void)dh;
12756
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
12757
}
12758
#endif
12759
12760
#ifndef NO_WOLFSSL_STUB
12761
/*** TBD ***/
12762
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
12763
{
12764
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
12765
    return NULL;
12766
}
12767
#endif
12768
12769
12770
#if !defined(NETOS)
12771
void wolfSSL_ERR_load_SSL_strings(void)
12772
{
12773
12774
}
12775
#endif
12776
12777
#ifdef HAVE_MAX_FRAGMENT
12778
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
12779
/**
12780
 * Set max fragment tls extension
12781
 * @param c a pointer to WOLFSSL_CTX object
12782
 * @param mode maximum fragment length mode
12783
 * @return 1 on success, otherwise 0 or negative error code
12784
 */
12785
int wolfSSL_CTX_set_tlsext_max_fragment_length(WOLFSSL_CTX *c,
12786
                                               unsigned char mode)
12787
{
12788
    if (c == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
12789
        return BAD_FUNC_ARG;
12790
12791
    return wolfSSL_CTX_UseMaxFragment(c, mode);
12792
}
12793
/**
12794
 * Set max fragment tls extension
12795
 * @param c a pointer to WOLFSSL object
12796
 * @param mode maximum fragment length mode
12797
 * @return 1 on success, otherwise 0 or negative error code
12798
 */
12799
int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s, unsigned char mode)
12800
{
12801
    if (s == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
12802
        return BAD_FUNC_ARG;
12803
12804
    return wolfSSL_UseMaxFragment(s, mode);
12805
}
12806
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
12807
#endif /* HAVE_MAX_FRAGMENT */
12808
12809
#endif /* OPENSSL_EXTRA */
12810
12811
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
12812
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
12813
{
12814
    byte len = 0;
12815
12816
    WOLFSSL_ENTER("wolfSSL_get_finished");
12817
12818
    if (!ssl || !buf || count < TLS_FINISHED_SZ) {
12819
        WOLFSSL_MSG("Bad parameter");
12820
        return WOLFSSL_FAILURE;
12821
    }
12822
12823
    if (ssl->options.side == WOLFSSL_SERVER_END) {
12824
        len = ssl->serverFinished_len;
12825
        XMEMCPY(buf, ssl->serverFinished, len);
12826
    }
12827
    else {
12828
        len = ssl->clientFinished_len;
12829
        XMEMCPY(buf, ssl->clientFinished, len);
12830
    }
12831
    return len;
12832
}
12833
12834
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
12835
{
12836
    byte len = 0;
12837
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
12838
12839
    if (!ssl || !buf || count < TLS_FINISHED_SZ) {
12840
        WOLFSSL_MSG("Bad parameter");
12841
        return WOLFSSL_FAILURE;
12842
    }
12843
12844
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
12845
        len = ssl->serverFinished_len;
12846
        XMEMCPY(buf, ssl->serverFinished, len);
12847
    }
12848
    else {
12849
        len = ssl->clientFinished_len;
12850
        XMEMCPY(buf, ssl->clientFinished, len);
12851
    }
12852
12853
    return len;
12854
}
12855
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
12856
12857
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
12858
    defined(OPENSSL_ALL)
12859
long wolfSSL_get_verify_result(const WOLFSSL *ssl)
12860
{
12861
    if (ssl == NULL) {
12862
        return WOLFSSL_FAILURE;
12863
    }
12864
12865
    return (long)ssl->peerVerifyRet;
12866
}
12867
#endif
12868
12869
#ifdef OPENSSL_EXTRA
12870
12871
#ifndef NO_WOLFSSL_STUB
12872
/* shows the number of accepts attempted by CTX in it's lifetime */
12873
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
12874
{
12875
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
12876
    (void)ctx;
12877
    return 0;
12878
}
12879
#endif
12880
12881
#ifndef NO_WOLFSSL_STUB
12882
/* shows the number of connects attempted CTX in it's lifetime */
12883
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
12884
{
12885
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
12886
    (void)ctx;
12887
    return 0;
12888
}
12889
#endif
12890
12891
12892
#ifndef NO_WOLFSSL_STUB
12893
/* shows the number of accepts completed by CTX in it's lifetime */
12894
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
12895
{
12896
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
12897
    (void)ctx;
12898
    return 0;
12899
}
12900
#endif
12901
12902
12903
#ifndef NO_WOLFSSL_STUB
12904
/* shows the number of connects completed by CTX in it's lifetime */
12905
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
12906
{
12907
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
12908
    (void)ctx;
12909
    return 0;
12910
}
12911
#endif
12912
12913
12914
#ifndef NO_WOLFSSL_STUB
12915
/* shows the number of renegotiation accepts attempted by CTX */
12916
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
12917
{
12918
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
12919
    (void)ctx;
12920
    return 0;
12921
}
12922
#endif
12923
12924
12925
#ifndef NO_WOLFSSL_STUB
12926
/* shows the number of renegotiation accepts attempted by CTX */
12927
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
12928
{
12929
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
12930
    (void)ctx;
12931
    return 0;
12932
}
12933
#endif
12934
12935
12936
#ifndef NO_WOLFSSL_STUB
12937
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
12938
{
12939
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
12940
    (void)ctx;
12941
    return 0;
12942
}
12943
#endif
12944
12945
12946
#ifndef NO_WOLFSSL_STUB
12947
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
12948
{
12949
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
12950
    (void)ctx;
12951
    return 0;
12952
}
12953
#endif
12954
12955
12956
#ifndef NO_WOLFSSL_STUB
12957
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
12958
{
12959
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
12960
    (void)ctx;
12961
    return 0;
12962
}
12963
#endif
12964
12965
12966
#ifndef NO_WOLFSSL_STUB
12967
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
12968
{
12969
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
12970
    (void)ctx;
12971
    return 0;
12972
}
12973
#endif
12974
12975
12976
#ifndef NO_WOLFSSL_STUB
12977
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
12978
{
12979
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
12980
    (void)ctx;
12981
    return 0;
12982
}
12983
#endif
12984
12985
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
12986
{
12987
    if (ssl == NULL) {
12988
        return WOLFSSL_FAILURE;
12989
    }
12990
12991
    return ssl->readAhead;
12992
}
12993
12994
12995
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
12996
{
12997
    if (ssl == NULL) {
12998
        return WOLFSSL_FAILURE;
12999
    }
13000
13001
    ssl->readAhead = (byte)v;
13002
13003
    return WOLFSSL_SUCCESS;
13004
}
13005
13006
13007
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
13008
{
13009
    if (ctx == NULL) {
13010
        return WOLFSSL_FAILURE;
13011
    }
13012
13013
    return ctx->readAhead;
13014
}
13015
13016
13017
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
13018
{
13019
    if (ctx == NULL) {
13020
        return WOLFSSL_FAILURE;
13021
    }
13022
13023
    ctx->readAhead = (byte)v;
13024
13025
    return WOLFSSL_SUCCESS;
13026
}
13027
13028
13029
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
13030
        void* arg)
13031
{
13032
    if (ctx == NULL) {
13033
        return WOLFSSL_FAILURE;
13034
    }
13035
13036
    ctx->userPRFArg = arg;
13037
    return WOLFSSL_SUCCESS;
13038
}
13039
13040
#endif /* OPENSSL_EXTRA */
13041
13042
#if defined(OPENSSL_EXTRA) && defined(KEEP_PEER_CERT) && \
13043
    defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM)
13044
int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname)
13045
{
13046
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
13047
13048
    WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file");
13049
    if (ssl != NULL && fname != NULL)
13050
    {
13051
    #ifdef WOLFSSL_SMALL_STACK
13052
        byte           staticBuffer[1]; /* force heap usage */
13053
    #else
13054
        byte           staticBuffer[FILE_BUFFER_SIZE];
13055
    #endif
13056
        byte*          myBuffer  = staticBuffer;
13057
        int            dynamic   = 0;
13058
        XFILE          file;
13059
        long           sz        = 0;
13060
        WOLFSSL_CTX*   ctx       = ssl->ctx;
13061
        WOLFSSL_X509*  peer_cert = &ssl->peerCert;
13062
        DerBuffer*     fileDer = NULL;
13063
13064
        file = XFOPEN(fname, "rb");
13065
        if (file == XBADFILE)
13066
            return WOLFSSL_BAD_FILE;
13067
13068
        if (XFSEEK(file, 0, XSEEK_END) != 0) {
13069
            XFCLOSE(file);
13070
            return WOLFSSL_BAD_FILE;
13071
        }
13072
        sz = XFTELL(file);
13073
        if (XFSEEK(file, 0, XSEEK_SET) != 0) {
13074
            XFCLOSE(file);
13075
            return WOLFSSL_BAD_FILE;
13076
        }
13077
13078
        if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) {
13079
            WOLFSSL_MSG("cmp_peer_cert_to_file size error");
13080
            XFCLOSE(file);
13081
            return WOLFSSL_BAD_FILE;
13082
        }
13083
13084
        if (sz > (long)sizeof(staticBuffer)) {
13085
            WOLFSSL_MSG("Getting dynamic buffer");
13086
            myBuffer = (byte*)XMALLOC((size_t)sz, ctx->heap, DYNAMIC_TYPE_FILE);
13087
            dynamic = 1;
13088
        }
13089
13090
        if ((myBuffer != NULL) &&
13091
            (sz > 0) &&
13092
            (XFREAD(myBuffer, 1, (size_t)sz, file) == (size_t)sz) &&
13093
            (PemToDer(myBuffer, (long)sz, CERT_TYPE,
13094
                      &fileDer, ctx->heap, NULL, NULL) == 0) &&
13095
            (fileDer->length != 0) &&
13096
            (fileDer->length == peer_cert->derCert->length) &&
13097
            (XMEMCMP(peer_cert->derCert->buffer, fileDer->buffer,
13098
                                                fileDer->length) == 0))
13099
        {
13100
            ret = 0;
13101
        }
13102
13103
        FreeDer(&fileDer);
13104
13105
        if (dynamic)
13106
            XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
13107
13108
        XFCLOSE(file);
13109
    }
13110
13111
    return ret;
13112
}
13113
#endif
13114
13115
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
13116
const WOLFSSL_ObjectInfo wolfssl_object_info[] = {
13117
#ifndef NO_CERTS
13118
    /* oidCertExtType */
13119
    { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType,
13120
      "basicConstraints", "X509v3 Basic Constraints"},
13121
    { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName",
13122
      "X509v3 Subject Alternative Name"},
13123
    { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType,
13124
      "crlDistributionPoints", "X509v3 CRL Distribution Points"},
13125
    { WC_NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess",
13126
      "Authority Information Access"},
13127
    { WC_NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType,
13128
      "authorityKeyIdentifier", "X509v3 Authority Key Identifier"},
13129
    { WC_NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType,
13130
      "subjectKeyIdentifier", "X509v3 Subject Key Identifier"},
13131
    { WC_NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage",
13132
      "X509v3 Key Usage"},
13133
    { WC_NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType,
13134
      "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"},
13135
    { WC_NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType,
13136
      "extendedKeyUsage", "X509v3 Extended Key Usage"},
13137
    { WC_NID_name_constraints, NAME_CONS_OID, oidCertExtType,
13138
      "nameConstraints", "X509v3 Name Constraints"},
13139
    { WC_NID_certificate_policies, CERT_POLICY_OID, oidCertExtType,
13140
      "certificatePolicies", "X509v3 Certificate Policies"},
13141
13142
    /* oidCertAuthInfoType */
13143
    { WC_NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP",
13144
      "OCSP"},
13145
    { WC_NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType,
13146
      "caIssuers", "CA Issuers"},
13147
13148
    /* oidCertPolicyType */
13149
    { WC_NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy",
13150
      "X509v3 Any Policy"},
13151
13152
    /* oidCertAltNameType */
13153
    { WC_NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""},
13154
13155
    /* oidCertKeyUseType */
13156
    { WC_NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType,
13157
      "anyExtendedKeyUsage", "Any Extended Key Usage"},
13158
    { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType,
13159
      "serverAuth", "TLS Web Server Authentication"},
13160
    { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType,
13161
      "clientAuth", "TLS Web Client Authentication"},
13162
    { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType,
13163
      "OCSPSigning", "OCSP Signing"},
13164
13165
    /* oidCertNameType */
13166
    { WC_NID_commonName, WC_NAME_COMMON_NAME_OID, oidCertNameType,
13167
      "CN", "commonName"},
13168
#if !defined(WOLFSSL_CERT_REQ)
13169
    { WC_NID_surname, WC_NAME_SURNAME_OID, oidCertNameType, "SN", "surname"},
13170
#endif
13171
    { WC_NID_serialNumber, WC_NAME_SERIAL_NUMBER_OID, oidCertNameType,
13172
      "serialNumber", "serialNumber"},
13173
    { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"},
13174
    { WC_NID_countryName, WC_NAME_COUNTRY_NAME_OID, oidCertNameType,
13175
      "C", "countryName"},
13176
    { WC_NID_localityName, WC_NAME_LOCALITY_NAME_OID, oidCertNameType,
13177
      "L", "localityName"},
13178
    { WC_NID_stateOrProvinceName, WC_NAME_STATE_NAME_OID, oidCertNameType,
13179
      "ST", "stateOrProvinceName"},
13180
    { WC_NID_streetAddress, WC_NAME_STREET_ADDRESS_OID, oidCertNameType,
13181
      "street", "streetAddress"},
13182
    { WC_NID_organizationName, WC_NAME_ORGANIZATION_NAME_OID, oidCertNameType,
13183
      "O", "organizationName"},
13184
    { WC_NID_organizationalUnitName, WC_NAME_ORGANIZATION_UNIT_NAME_OID,
13185
      oidCertNameType, "OU", "organizationalUnitName"},
13186
    { WC_NID_title, WC_NAME_TITLE_OID, oidCertNameType, "title", "title"},
13187
    { WC_NID_description, WC_NAME_DESCRIPTION_OID, oidCertNameType,
13188
      "description", "description"},
13189
    { WC_NID_emailAddress, WC_NAME_EMAIL_ADDRESS_OID, oidCertNameType,
13190
      "emailAddress", "emailAddress"},
13191
    { WC_NID_domainComponent, WC_NAME_DOMAIN_COMPONENT_OID, oidCertNameType,
13192
      "DC", "domainComponent"},
13193
    { WC_NID_rfc822Mailbox, WC_NAME_RFC822_MAILBOX_OID, oidCertNameType,
13194
      "rfc822Mailbox", "rfc822Mailbox"},
13195
    { WC_NID_favouriteDrink, WC_NAME_FAVOURITE_DRINK_OID, oidCertNameType,
13196
      "favouriteDrink", "favouriteDrink"},
13197
    { WC_NID_businessCategory, WC_NAME_BUSINESS_CATEGORY_OID, oidCertNameType,
13198
      "businessCategory", "businessCategory"},
13199
    { WC_NID_jurisdictionCountryName, WC_NAME_JURIS_COUNTRY_OID,
13200
      oidCertNameType, "jurisdictionC", "jurisdictionCountryName"},
13201
    { WC_NID_jurisdictionStateOrProvinceName, WC_NAME_JURIS_STATE_PROV_OID,
13202
      oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"},
13203
    { WC_NID_postalCode, WC_NAME_POSTAL_CODE_OID, oidCertNameType, "postalCode",
13204
      "postalCode"},
13205
    { WC_NID_userId, WC_NAME_USER_ID_OID, oidCertNameType, "UID", "userId"},
13206
    { WC_NID_netscape_cert_type, NETSCAPE_CT_OID, oidCertNameType,
13207
      "nsCertType", "Netscape Cert Type"},
13208
13209
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL)
13210
    { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID,
13211
            oidCsrAttrType, "challengePassword", "challengePassword"},
13212
    { WC_NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID,
13213
        oidCsrAttrType, "contentType", "contentType" },
13214
    { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID,
13215
        oidCsrAttrType, "unstructuredName", "unstructuredName" },
13216
    { WC_NID_name, WC_NAME_NAME_OID, oidCsrAttrType, "name", "name" },
13217
    { WC_NID_surname, SURNAME_OID,
13218
        oidCsrAttrType, "surname", "surname" },
13219
    { WC_NID_givenName, WC_NAME_GIVEN_NAME_OID,
13220
        oidCsrAttrType, "givenName", "givenName" },
13221
    { WC_NID_initials, WC_NAME_INITIALIS_OID,
13222
        oidCsrAttrType, "initials", "initials" },
13223
    { WC_NID_dnQualifier, DNQUALIFIER_OID,
13224
        oidCsrAttrType, "dnQualifer", "dnQualifier" },
13225
#endif
13226
#endif
13227
#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */
13228
        /* oidHashType */
13229
    #ifdef WOLFSSL_MD2
13230
        { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"},
13231
    #endif
13232
    #ifndef NO_MD4
13233
        { WC_NID_md4, MD4h, oidHashType, "MD4", "md4"},
13234
    #endif
13235
    #ifndef NO_MD5
13236
        { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"},
13237
    #endif
13238
    #ifndef NO_SHA
13239
        { WC_NID_sha1, SHAh, oidHashType, "SHA1", "sha1"},
13240
    #endif
13241
    #ifdef WOLFSSL_SHA224
13242
        { WC_NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"},
13243
    #endif
13244
    #ifndef NO_SHA256
13245
        { WC_NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"},
13246
    #endif
13247
    #ifdef WOLFSSL_SHA384
13248
        { WC_NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"},
13249
    #endif
13250
    #ifdef WOLFSSL_SHA512
13251
        { WC_NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"},
13252
    #endif
13253
    #ifdef WOLFSSL_SHA3
13254
        #ifndef WOLFSSL_NOSHA3_224
13255
        { WC_NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"},
13256
        #endif
13257
        #ifndef WOLFSSL_NOSHA3_256
13258
        { WC_NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"},
13259
        #endif
13260
        #ifndef WOLFSSL_NOSHA3_384
13261
        { WC_NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"},
13262
        #endif
13263
        #ifndef WOLFSSL_NOSHA3_512
13264
        { WC_NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"},
13265
        #endif
13266
    #endif /* WOLFSSL_SHA3 */
13267
    #ifdef WOLFSSL_SM3
13268
        { WC_NID_sm3, SM3h, oidHashType, "SM3", "sm3"},
13269
    #endif
13270
    #ifdef WOLFSSL_SHAKE128
13271
        { WC_NID_shake128, SHAKE128h, oidHashType, "SHAKE128", "shake128"},
13272
    #endif
13273
    #ifdef WOLFSSL_SHAKE256
13274
        { WC_NID_shake256, SHAKE256h, oidHashType, "SHAKE256", "shake256"},
13275
    #endif
13276
        /* oidSigType */
13277
    #ifndef NO_DSA
13278
        #ifndef NO_SHA
13279
        { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType,
13280
          "DSA-SHA1", "dsaWithSHA1"},
13281
        { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256",
13282
          "dsa_with_SHA256"},
13283
        #endif
13284
    #endif /* NO_DSA */
13285
    #ifndef NO_RSA
13286
        #ifdef WOLFSSL_MD2
13287
        { WC_NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2",
13288
          "md2WithRSAEncryption"},
13289
        #endif
13290
        #ifndef NO_MD5
13291
        { WC_NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5",
13292
          "md5WithRSAEncryption"},
13293
        #endif
13294
        #ifndef NO_SHA
13295
        { WC_NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1",
13296
          "sha1WithRSAEncryption"},
13297
        #endif
13298
        #ifdef WOLFSSL_SHA224
13299
        { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType,
13300
          "RSA-SHA224", "sha224WithRSAEncryption"},
13301
        #endif
13302
        #ifndef NO_SHA256
13303
        { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType,
13304
          "RSA-SHA256", "sha256WithRSAEncryption"},
13305
        #endif
13306
        #ifdef WOLFSSL_SHA384
13307
        { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType,
13308
          "RSA-SHA384", "sha384WithRSAEncryption"},
13309
        #endif
13310
        #ifdef WOLFSSL_SHA512
13311
        { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType,
13312
          "RSA-SHA512", "sha512WithRSAEncryption"},
13313
        #endif
13314
        #ifdef WOLFSSL_SHA3
13315
        #ifndef WOLFSSL_NOSHA3_224
13316
        { WC_NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224",
13317
          "sha3-224WithRSAEncryption"},
13318
        #endif
13319
        #ifndef WOLFSSL_NOSHA3_256
13320
        { WC_NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256",
13321
          "sha3-256WithRSAEncryption"},
13322
        #endif
13323
        #ifndef WOLFSSL_NOSHA3_384
13324
        { WC_NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384",
13325
          "sha3-384WithRSAEncryption"},
13326
        #endif
13327
        #ifndef WOLFSSL_NOSHA3_512
13328
        { WC_NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512",
13329
          "sha3-512WithRSAEncryption"},
13330
        #endif
13331
        #endif
13332
        #ifdef WC_RSA_PSS
13333
        { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType,
13334
          "RSASSA-PSS", "rsassaPss" },
13335
        #endif
13336
    #endif /* NO_RSA */
13337
    #ifdef HAVE_ECC
13338
        #ifndef NO_SHA
13339
        { WC_NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1",
13340
          "shaWithECDSA"},
13341
        #endif
13342
        #ifdef WOLFSSL_SHA224
13343
        { WC_NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType,
13344
          "ecdsa-with-SHA224","sha224WithECDSA"},
13345
        #endif
13346
        #ifndef NO_SHA256
13347
        { WC_NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType,
13348
          "ecdsa-with-SHA256","sha256WithECDSA"},
13349
        #endif
13350
        #ifdef WOLFSSL_SHA384
13351
        { WC_NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType,
13352
          "ecdsa-with-SHA384","sha384WithECDSA"},
13353
        #endif
13354
        #ifdef WOLFSSL_SHA512
13355
        { WC_NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType,
13356
          "ecdsa-with-SHA512","sha512WithECDSA"},
13357
        #endif
13358
        #ifdef WOLFSSL_SHA3
13359
        #ifndef WOLFSSL_NOSHA3_224
13360
        { WC_NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType,
13361
          "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"},
13362
        #endif
13363
        #ifndef WOLFSSL_NOSHA3_256
13364
        { WC_NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType,
13365
          "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"},
13366
        #endif
13367
        #ifndef WOLFSSL_NOSHA3_384
13368
        { WC_NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType,
13369
          "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"},
13370
        #endif
13371
        #ifndef WOLFSSL_NOSHA3_512
13372
        { WC_NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType,
13373
          "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"},
13374
        #endif
13375
        #endif
13376
    #endif /* HAVE_ECC */
13377
13378
        /* oidKeyType */
13379
    #ifndef NO_DSA
13380
        { WC_NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"},
13381
    #endif /* NO_DSA */
13382
    #ifndef NO_RSA
13383
        { WC_NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption",
13384
          "rsaEncryption"},
13385
    #ifdef WC_RSA_PSS
13386
        { WC_NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"},
13387
    #endif
13388
    #endif /* NO_RSA */
13389
    #ifdef HAVE_ECC
13390
        { WC_NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey",
13391
                                                        "id-ecPublicKey"},
13392
    #endif /* HAVE_ECC */
13393
    #ifndef NO_DH
13394
        { WC_NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement",
13395
          "dhKeyAgreement"},
13396
    #endif
13397
    #ifdef HAVE_ED448
13398
        { WC_NID_ED448, ED448k,  oidKeyType, "ED448", "ED448"},
13399
    #endif
13400
    #ifdef HAVE_ED25519
13401
        { WC_NID_ED25519, ED25519k,  oidKeyType, "ED25519", "ED25519"},
13402
    #endif
13403
    #ifdef HAVE_FALCON
13404
        { CTC_FALCON_LEVEL1, FALCON_LEVEL1k,  oidKeyType, "Falcon Level 1",
13405
                                                          "Falcon Level 1"},
13406
        { CTC_FALCON_LEVEL5, FALCON_LEVEL5k,  oidKeyType, "Falcon Level 5",
13407
                                                          "Falcon Level 5"},
13408
    #endif /* HAVE_FALCON */
13409
    #ifdef HAVE_DILITHIUM
13410
    #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
13411
        { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k,  oidKeyType,
13412
          "Dilithium Level 2", "Dilithium Level 2"},
13413
        { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k,  oidKeyType,
13414
          "Dilithium Level 3", "Dilithium Level 3"},
13415
        { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k,  oidKeyType,
13416
          "Dilithium Level 5", "Dilithium Level 5"},
13417
    #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
13418
        { CTC_ML_DSA_LEVEL2, ML_DSA_LEVEL2k,  oidKeyType,
13419
          "ML-DSA 44", "ML-DSA 44"},
13420
        { CTC_ML_DSA_LEVEL3, ML_DSA_LEVEL3k,  oidKeyType,
13421
          "ML-DSA 65", "ML-DSA 65"},
13422
        { CTC_ML_DSA_LEVEL5, ML_DSA_LEVEL5k,  oidKeyType,
13423
          "ML-DSA 87", "ML-DSA 87"},
13424
    #endif /* HAVE_DILITHIUM */
13425
13426
        /* oidCurveType */
13427
    #ifdef HAVE_ECC
13428
        { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType,
13429
          "prime192v1", "prime192v1"},
13430
        { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType,
13431
          "prime192v2", "prime192v2"},
13432
        { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType,
13433
          "prime192v3", "prime192v3"},
13434
13435
        { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType,
13436
          "prime239v1", "prime239v1"},
13437
        { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType,
13438
          "prime239v2", "prime239v2"},
13439
        { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType,
13440
          "prime239v3", "prime239v3"},
13441
13442
        { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType,
13443
          "prime256v1", "prime256v1"},
13444
13445
        { WC_NID_secp112r1, ECC_SECP112R1_OID,  oidCurveType, "secp112r1",
13446
          "secp112r1"},
13447
        { WC_NID_secp112r2, ECC_SECP112R2_OID,  oidCurveType, "secp112r2",
13448
          "secp112r2"},
13449
13450
        { WC_NID_secp128r1, ECC_SECP128R1_OID,  oidCurveType, "secp128r1",
13451
          "secp128r1"},
13452
        { WC_NID_secp128r2, ECC_SECP128R2_OID,  oidCurveType, "secp128r2",
13453
          "secp128r2"},
13454
13455
        { WC_NID_secp160r1, ECC_SECP160R1_OID,  oidCurveType, "secp160r1",
13456
          "secp160r1"},
13457
        { WC_NID_secp160r2, ECC_SECP160R2_OID,  oidCurveType, "secp160r2",
13458
          "secp160r2"},
13459
13460
        { WC_NID_secp224r1, ECC_SECP224R1_OID,  oidCurveType, "secp224r1",
13461
          "secp224r1"},
13462
        { WC_NID_secp384r1, ECC_SECP384R1_OID,  oidCurveType, "secp384r1",
13463
          "secp384r1"},
13464
        { WC_NID_secp521r1, ECC_SECP521R1_OID,  oidCurveType, "secp521r1",
13465
          "secp521r1"},
13466
13467
        { WC_NID_secp160k1, ECC_SECP160K1_OID,  oidCurveType, "secp160k1",
13468
          "secp160k1"},
13469
        { WC_NID_secp192k1, ECC_SECP192K1_OID,  oidCurveType, "secp192k1",
13470
          "secp192k1"},
13471
        { WC_NID_secp224k1, ECC_SECP224K1_OID,  oidCurveType, "secp224k1",
13472
          "secp224k1"},
13473
        { WC_NID_secp256k1, ECC_SECP256K1_OID,  oidCurveType, "secp256k1",
13474
          "secp256k1"},
13475
13476
        { WC_NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID,  oidCurveType,
13477
          "brainpoolP160r1", "brainpoolP160r1"},
13478
        { WC_NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID,  oidCurveType,
13479
          "brainpoolP192r1", "brainpoolP192r1"},
13480
        { WC_NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID,  oidCurveType,
13481
          "brainpoolP224r1", "brainpoolP224r1"},
13482
        { WC_NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID,  oidCurveType,
13483
          "brainpoolP256r1", "brainpoolP256r1"},
13484
        { WC_NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID,  oidCurveType,
13485
          "brainpoolP320r1", "brainpoolP320r1"},
13486
        { WC_NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID,  oidCurveType,
13487
          "brainpoolP384r1", "brainpoolP384r1"},
13488
        { WC_NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID,  oidCurveType,
13489
          "brainpoolP512r1", "brainpoolP512r1"},
13490
13491
    #ifdef WOLFSSL_SM2
13492
        { WC_NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"},
13493
    #endif
13494
    #endif /* HAVE_ECC */
13495
13496
        /* oidBlkType */
13497
    #ifdef WOLFSSL_AES_128
13498
        { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"},
13499
    #endif
13500
    #ifdef WOLFSSL_AES_192
13501
        { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"},
13502
    #endif
13503
    #ifdef WOLFSSL_AES_256
13504
        { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"},
13505
    #endif
13506
    #ifndef NO_DES3
13507
        { WC_NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"},
13508
        { WC_NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"},
13509
    #endif /* !NO_DES3 */
13510
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
13511
        { WC_NID_chacha20_poly1305, WC_NID_chacha20_poly1305, oidBlkType,
13512
          "ChaCha20-Poly1305", "chacha20-poly1305"},
13513
    #endif
13514
13515
        /* oidOcspType */
13516
    #ifdef HAVE_OCSP
13517
        { WC_NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType,
13518
          "basicOCSPResponse", "Basic OCSP Response"},
13519
        { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"},
13520
    #endif /* HAVE_OCSP */
13521
13522
    #ifndef NO_PWDBASED
13523
        /* oidKdfType */
13524
        { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"},
13525
13526
        /* oidPBEType */
13527
        { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType,
13528
          "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"},
13529
        { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES",
13530
          "pbeWithSHA1AndDES-CBC"},
13531
        { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES",
13532
          "pbeWithSHA1And3-KeyTripleDES-CBC"},
13533
    #endif
13534
13535
        /* oidKeyWrapType */
13536
    #ifdef WOLFSSL_AES_128
13537
        { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap",
13538
          "aes128-wrap"},
13539
    #endif
13540
    #ifdef WOLFSSL_AES_192
13541
        { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap",
13542
          "aes192-wrap"},
13543
    #endif
13544
    #ifdef WOLFSSL_AES_256
13545
        { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap",
13546
          "aes256-wrap"},
13547
    #endif
13548
13549
    #ifndef NO_PKCS7
13550
        #ifndef NO_DH
13551
        /* oidCmsKeyAgreeType */
13552
            #ifndef NO_SHA
13553
        { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme,
13554
          oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme",
13555
          "dhSinglePass-stdDH-sha1kdf-scheme"},
13556
            #endif
13557
            #ifdef WOLFSSL_SHA224
13558
        { dhSinglePass_stdDH_sha224kdf_scheme,
13559
          dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType,
13560
          "dhSinglePass-stdDH-sha224kdf-scheme",
13561
          "dhSinglePass-stdDH-sha224kdf-scheme"},
13562
            #endif
13563
            #ifndef NO_SHA256
13564
        { dhSinglePass_stdDH_sha256kdf_scheme,
13565
          dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType,
13566
          "dhSinglePass-stdDH-sha256kdf-scheme",
13567
          "dhSinglePass-stdDH-sha256kdf-scheme"},
13568
            #endif
13569
            #ifdef WOLFSSL_SHA384
13570
        { dhSinglePass_stdDH_sha384kdf_scheme,
13571
          dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType,
13572
          "dhSinglePass-stdDH-sha384kdf-scheme",
13573
          "dhSinglePass-stdDH-sha384kdf-scheme"},
13574
            #endif
13575
            #ifdef WOLFSSL_SHA512
13576
        { dhSinglePass_stdDH_sha512kdf_scheme,
13577
          dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType,
13578
          "dhSinglePass-stdDH-sha512kdf-scheme",
13579
          "dhSinglePass-stdDH-sha512kdf-scheme"},
13580
            #endif
13581
        #endif
13582
    #endif
13583
    #if defined(WOLFSSL_APACHE_HTTPD)
13584
        /* "1.3.6.1.5.5.7.8.7" */
13585
        { WC_NID_id_on_dnsSRV, WOLFSSL_DNS_SRV_SUM, oidCertNameType,
13586
            WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV },
13587
13588
        /* "1.3.6.1.4.1.311.20.2.3" */
13589
        { WC_NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN,
13590
            WOLFSSL_LN_MS_UPN },
13591
13592
        /* "1.3.6.1.5.5.7.1.24" */
13593
        { WC_NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType,
13594
            WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE },
13595
    #endif
13596
#endif /* OPENSSL_EXTRA */
13597
};
13598
13599
#define WOLFSSL_OBJECT_INFO_SZ \
13600
                (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info))
13601
const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ;
13602
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
13603
13604
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
13605
/* Free the dynamically allocated data.
13606
 *
13607
 * p  Pointer to dynamically allocated memory.
13608
 */
13609
void wolfSSL_OPENSSL_free(void* p)
13610
{
13611
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
13612
13613
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
13614
}
13615
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
13616
13617
#ifdef OPENSSL_EXTRA
13618
13619
void *wolfSSL_OPENSSL_malloc(size_t a)
13620
{
13621
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
13622
}
13623
13624
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
13625
{
13626
    /* 'char' is unsigned on some platforms. */
13627
    return (int)(signed char)HexCharToByte((char)c);
13628
}
13629
13630
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
13631
{
13632
    unsigned char* targetBuf;
13633
    int srcDigitHigh = 0;
13634
    int srcDigitLow = 0;
13635
    size_t srcLen;
13636
    size_t srcIdx = 0;
13637
    long targetIdx = 0;
13638
13639
    srcLen = XSTRLEN(str);
13640
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
13641
    if (targetBuf == NULL) {
13642
        return NULL;
13643
    }
13644
13645
    while (srcIdx < srcLen) {
13646
        if (str[srcIdx] == ':') {
13647
            srcIdx++;
13648
            continue;
13649
        }
13650
13651
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
13652
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
13653
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
13654
            WOLFSSL_MSG("Invalid hex character.");
13655
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
13656
            return NULL;
13657
        }
13658
13659
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
13660
                                                  srcDigitLow       );
13661
    }
13662
13663
    if (len != NULL)
13664
        *len = targetIdx;
13665
13666
    return targetBuf;
13667
}
13668
13669
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
13670
{
13671
    (void)opts;
13672
    (void)settings;
13673
    return wolfSSL_library_init();
13674
}
13675
13676
int wolfSSL_OPENSSL_init_crypto(word64 opts,
13677
    const WOLFSSL_INIT_SETTINGS* settings)
13678
{
13679
    (void)opts;
13680
    (void)settings;
13681
    return wolfSSL_library_init();
13682
}
13683
13684
/* Colon separated list of <public key>+<digest> algorithms.
13685
 * Replaces list in context.
13686
 */
13687
int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list)
13688
{
13689
    WOLFSSL_MSG("wolfSSL_CTX_set1_sigalg_list");
13690
13691
    if (ctx == NULL || list == NULL) {
13692
        WOLFSSL_MSG("Bad function arguments");
13693
        return WOLFSSL_FAILURE;
13694
    }
13695
13696
    if (AllocateCtxSuites(ctx) != 0)
13697
        return WOLFSSL_FAILURE;
13698
13699
    return SetSuitesHashSigAlgo(ctx->suites, list);
13700
}
13701
13702
/* Colon separated list of <public key>+<digest> algorithms.
13703
 * Replaces list in SSL.
13704
 */
13705
int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list)
13706
{
13707
    WOLFSSL_MSG("wolfSSL_set1_sigalg_list");
13708
13709
    if (ssl == NULL || list == NULL) {
13710
        WOLFSSL_MSG("Bad function arguments");
13711
        return WOLFSSL_FAILURE;
13712
    }
13713
13714
    if (AllocateSuites(ssl) != 0)
13715
        return WOLFSSL_FAILURE;
13716
13717
    return SetSuitesHashSigAlgo(ssl->suites, list);
13718
}
13719
13720
static int HashToNid(byte hashAlgo, int* nid)
13721
{
13722
    int ret = WOLFSSL_SUCCESS;
13723
13724
    /* Cast for compiler to check everything is implemented */
13725
    switch ((enum wc_MACAlgorithm)hashAlgo) {
13726
        case no_mac:
13727
        case rmd_mac:
13728
            *nid = WC_NID_undef;
13729
            break;
13730
        case md5_mac:
13731
            *nid = WC_NID_md5;
13732
            break;
13733
        case sha_mac:
13734
            *nid = WC_NID_sha1;
13735
            break;
13736
        case sha224_mac:
13737
            *nid = WC_NID_sha224;
13738
            break;
13739
        case sha256_mac:
13740
            *nid = WC_NID_sha256;
13741
            break;
13742
        case sha384_mac:
13743
            *nid = WC_NID_sha384;
13744
            break;
13745
        case sha512_mac:
13746
            *nid = WC_NID_sha512;
13747
            break;
13748
        case blake2b_mac:
13749
            *nid = WC_NID_blake2b512;
13750
            break;
13751
        case sm3_mac:
13752
            *nid = WC_NID_sm3;
13753
            break;
13754
        default:
13755
            ret = WOLFSSL_FAILURE;
13756
            break;
13757
    }
13758
13759
    return ret;
13760
}
13761
13762
static int SaToNid(byte sa, int* nid)
13763
{
13764
    int ret = WOLFSSL_SUCCESS;
13765
    /* Cast for compiler to check everything is implemented */
13766
    switch ((enum SignatureAlgorithm)sa) {
13767
        case anonymous_sa_algo:
13768
            *nid = WC_NID_undef;
13769
            break;
13770
        case rsa_sa_algo:
13771
            *nid = WC_NID_rsaEncryption;
13772
            break;
13773
        case dsa_sa_algo:
13774
            *nid = WC_NID_dsa;
13775
            break;
13776
        case ecc_dsa_sa_algo:
13777
        case ecc_brainpool_sa_algo:
13778
            *nid = WC_NID_X9_62_id_ecPublicKey;
13779
            break;
13780
        case rsa_pss_sa_algo:
13781
            *nid = WC_NID_rsassaPss;
13782
            break;
13783
        case ed25519_sa_algo:
13784
#ifdef HAVE_ED25519
13785
            *nid = WC_NID_ED25519;
13786
#else
13787
            ret = WOLFSSL_FAILURE;
13788
#endif
13789
            break;
13790
        case rsa_pss_pss_algo:
13791
            *nid = WC_NID_rsassaPss;
13792
            break;
13793
        case ed448_sa_algo:
13794
#ifdef HAVE_ED448
13795
            *nid = WC_NID_ED448;
13796
#else
13797
            ret = WOLFSSL_FAILURE;
13798
#endif
13799
            break;
13800
        case falcon_level1_sa_algo:
13801
            *nid = CTC_FALCON_LEVEL1;
13802
            break;
13803
        case falcon_level5_sa_algo:
13804
            *nid = CTC_FALCON_LEVEL5;
13805
            break;
13806
        case dilithium_level2_sa_algo:
13807
            *nid = CTC_ML_DSA_LEVEL2;
13808
            break;
13809
        case dilithium_level3_sa_algo:
13810
            *nid = CTC_ML_DSA_LEVEL3;
13811
            break;
13812
        case dilithium_level5_sa_algo:
13813
            *nid = CTC_ML_DSA_LEVEL5;
13814
            break;
13815
        case sm2_sa_algo:
13816
            *nid = WC_NID_sm2;
13817
            break;
13818
        case invalid_sa_algo:
13819
        case any_sa_algo:
13820
        default:
13821
            ret = WOLFSSL_FAILURE;
13822
            break;
13823
    }
13824
    return ret;
13825
}
13826
13827
/* This API returns the hash selected. */
13828
int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid)
13829
{
13830
    WOLFSSL_MSG("wolfSSL_get_signature_nid");
13831
13832
    if (ssl == NULL || nid == NULL) {
13833
        WOLFSSL_MSG("Bad function arguments");
13834
        return WOLFSSL_FAILURE;
13835
    }
13836
13837
    return HashToNid(ssl->options.hashAlgo, nid);
13838
}
13839
13840
/* This API returns the signature selected. */
13841
int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid)
13842
{
13843
    WOLFSSL_MSG("wolfSSL_get_signature_type_nid");
13844
13845
    if (ssl == NULL || nid == NULL) {
13846
        WOLFSSL_MSG("Bad function arguments");
13847
        return WOLFSSL_FAILURE;
13848
    }
13849
13850
    return SaToNid(ssl->options.sigAlgo, nid);
13851
}
13852
13853
int wolfSSL_get_peer_signature_nid(WOLFSSL* ssl, int* nid)
13854
{
13855
    WOLFSSL_MSG("wolfSSL_get_peer_signature_nid");
13856
13857
    if (ssl == NULL || nid == NULL) {
13858
        WOLFSSL_MSG("Bad function arguments");
13859
        return WOLFSSL_FAILURE;
13860
    }
13861
13862
    return HashToNid(ssl->options.peerHashAlgo, nid);
13863
}
13864
13865
int wolfSSL_get_peer_signature_type_nid(const WOLFSSL* ssl, int* nid)
13866
{
13867
    WOLFSSL_MSG("wolfSSL_get_peer_signature_type_nid");
13868
13869
    if (ssl == NULL || nid == NULL) {
13870
        WOLFSSL_MSG("Bad function arguments");
13871
        return WOLFSSL_FAILURE;
13872
    }
13873
13874
    return SaToNid(ssl->options.peerSigAlgo, nid);
13875
}
13876
13877
#ifdef HAVE_ECC
13878
13879
#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
13880
int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list)
13881
{
13882
    if (!ctx || !list) {
13883
        return WOLFSSL_FAILURE;
13884
    }
13885
13886
    return set_curves_list(NULL, ctx, list, 0);
13887
}
13888
13889
int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list)
13890
{
13891
    if (!ssl || !list) {
13892
        return WOLFSSL_FAILURE;
13893
    }
13894
13895
    return set_curves_list(ssl, NULL, list, 0);
13896
}
13897
#endif /* WOLFSSL_TLS13 */
13898
13899
#endif /* HAVE_ECC */
13900
13901
#endif /* OPENSSL_EXTRA */
13902
13903
#ifdef WOLFSSL_ALT_CERT_CHAINS
13904
int wolfSSL_is_peer_alt_cert_chain(const WOLFSSL* ssl)
13905
{
13906
    int isUsing = 0;
13907
    if (ssl)
13908
        isUsing = ssl->options.usingAltCertChain;
13909
    return isUsing;
13910
}
13911
#endif /* WOLFSSL_ALT_CERT_CHAINS */
13912
13913
13914
#ifdef SESSION_CERTS
13915
13916
#ifdef WOLFSSL_ALT_CERT_CHAINS
13917
/* Get peer's alternate certificate chain */
13918
WOLFSSL_X509_CHAIN* wolfSSL_get_peer_alt_chain(WOLFSSL* ssl)
13919
{
13920
    WOLFSSL_ENTER("wolfSSL_get_peer_alt_chain");
13921
    if (ssl)
13922
        return &ssl->session->altChain;
13923
13924
    return 0;
13925
}
13926
#endif /* WOLFSSL_ALT_CERT_CHAINS */
13927
13928
13929
/* Get peer's certificate chain */
13930
WOLFSSL_X509_CHAIN* wolfSSL_get_peer_chain(WOLFSSL* ssl)
13931
{
13932
    WOLFSSL_ENTER("wolfSSL_get_peer_chain");
13933
    if (ssl)
13934
        return &ssl->session->chain;
13935
13936
    return 0;
13937
}
13938
13939
13940
/* Get peer's certificate chain total count */
13941
int wolfSSL_get_chain_count(WOLFSSL_X509_CHAIN* chain)
13942
{
13943
    WOLFSSL_ENTER("wolfSSL_get_chain_count");
13944
    if (chain)
13945
        return chain->count;
13946
13947
    return 0;
13948
}
13949
13950
13951
/* Get peer's ASN.1 DER certificate at index (idx) length in bytes */
13952
int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx)
13953
{
13954
    WOLFSSL_ENTER("wolfSSL_get_chain_length");
13955
    if (chain)
13956
        return chain->certs[idx].length;
13957
13958
    return 0;
13959
}
13960
13961
13962
/* Get peer's ASN.1 DER certificate at index (idx) */
13963
byte* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx)
13964
{
13965
    WOLFSSL_ENTER("wolfSSL_get_chain_cert");
13966
    if (chain)
13967
        return chain->certs[idx].buffer;
13968
13969
    return 0;
13970
}
13971
13972
13973
/* Get peer's wolfSSL X509 certificate at index (idx) */
13974
WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx)
13975
{
13976
    int          ret = 0;
13977
    WOLFSSL_X509* x509 = NULL;
13978
    WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
13979
13980
    WOLFSSL_ENTER("wolfSSL_get_chain_X509");
13981
    if (chain != NULL && idx < MAX_CHAIN_DEPTH) {
13982
    #ifdef WOLFSSL_SMALL_STACK
13983
        cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
13984
                                                       DYNAMIC_TYPE_DCERT);
13985
        if (cert != NULL)
13986
    #endif
13987
        {
13988
            InitDecodedCert(cert, chain->certs[idx].buffer,
13989
                                  (word32)chain->certs[idx].length, NULL);
13990
13991
            if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) != 0) {
13992
                WOLFSSL_MSG("Failed to parse cert");
13993
            }
13994
            else {
13995
                x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL,
13996
                                                             DYNAMIC_TYPE_X509);
13997
                if (x509 == NULL) {
13998
                    WOLFSSL_MSG("Failed alloc X509");
13999
                }
14000
                else {
14001
                    InitX509(x509, 1, NULL);
14002
14003
                    if ((ret = CopyDecodedToX509(x509, cert)) != 0) {
14004
                        WOLFSSL_MSG("Failed to copy decoded");
14005
                        wolfSSL_X509_free(x509);
14006
                        x509 = NULL;
14007
                    }
14008
                }
14009
            }
14010
14011
            FreeDecodedCert(cert);
14012
            WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
14013
        }
14014
    }
14015
    (void)ret;
14016
14017
    return x509;
14018
}
14019
14020
14021
/* Get peer's PEM certificate at index (idx), output to buffer if inLen big
14022
   enough else return error (-1). If buffer is NULL only calculate
14023
   outLen. Output length is in *outLen WOLFSSL_SUCCESS on ok */
14024
int  wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx,
14025
                               unsigned char* buf, int inLen, int* outLen)
14026
{
14027
#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
14028
    const char* header = NULL;
14029
    const char* footer = NULL;
14030
    int headerLen;
14031
    int footerLen;
14032
    int i;
14033
    int err;
14034
    word32 szNeeded = 0;
14035
14036
    WOLFSSL_ENTER("wolfSSL_get_chain_cert_pem");
14037
    if (!chain || !outLen || idx < 0 || idx >= wolfSSL_get_chain_count(chain))
14038
        return BAD_FUNC_ARG;
14039
14040
    err = wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer);
14041
    if (err != 0)
14042
        return err;
14043
14044
    headerLen = (int)XSTRLEN(header);
14045
    footerLen = (int)XSTRLEN(footer);
14046
14047
    /* Null output buffer return size needed in outLen */
14048
    if(!buf) {
14049
        if(Base64_Encode(chain->certs[idx].buffer,
14050
                    (word32)chain->certs[idx].length,
14051
                    NULL, &szNeeded) != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
14052
            return WOLFSSL_FAILURE;
14053
        *outLen = (int)szNeeded + headerLen + footerLen;
14054
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
14055
    }
14056
14057
    /* don't even try if inLen too short */
14058
    if (inLen < headerLen + footerLen + chain->certs[idx].length)
14059
        return BAD_FUNC_ARG;
14060
14061
    /* header */
14062
    if (XMEMCPY(buf, header, (size_t)headerLen) == NULL)
14063
        return WOLFSSL_FATAL_ERROR;
14064
14065
    i = headerLen;
14066
14067
    /* body */
14068
    *outLen = inLen;  /* input to Base64_Encode */
14069
    if ( (err = Base64_Encode(chain->certs[idx].buffer,
14070
                       (word32)chain->certs[idx].length, buf + i,
14071
                       (word32*)outLen)) < 0)
14072
        return err;
14073
    i += *outLen;
14074
14075
    /* footer */
14076
    if ( (i + footerLen) > inLen)
14077
        return BAD_FUNC_ARG;
14078
    if (XMEMCPY(buf + i, footer, (size_t)footerLen) == NULL)
14079
        return WOLFSSL_FATAL_ERROR;
14080
    *outLen += headerLen + footerLen;
14081
14082
    return WOLFSSL_SUCCESS;
14083
#else
14084
    (void)chain;
14085
    (void)idx;
14086
    (void)buf;
14087
    (void)inLen;
14088
    (void)outLen;
14089
    return WOLFSSL_FAILURE;
14090
#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
14091
}
14092
14093
#endif /* SESSION_CERTS */
14094
14095
#ifdef HAVE_FUZZER
14096
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
14097
{
14098
    if (ssl) {
14099
        ssl->fuzzerCb  = cbf;
14100
        ssl->fuzzerCtx = fCtx;
14101
    }
14102
}
14103
#endif
14104
14105
#ifndef NO_CERTS
14106
#ifdef  HAVE_PK_CALLBACKS
14107
14108
/* callback for premaster secret generation */
14109
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
14110
{
14111
    if (ctx)
14112
        ctx->GenPreMasterCb = cb;
14113
}
14114
/* Set premaster secret generation callback context */
14115
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
14116
{
14117
    if (ssl)
14118
        ssl->GenPreMasterCtx = ctx;
14119
}
14120
/* Get premaster secret generation callback context */
14121
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
14122
{
14123
    if (ssl)
14124
        return ssl->GenPreMasterCtx;
14125
14126
    return NULL;
14127
}
14128
14129
/* callback for master secret generation */
14130
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
14131
    CallbackGenMasterSecret cb)
14132
{
14133
    if (ctx)
14134
        ctx->GenMasterCb = cb;
14135
}
14136
/* Set master secret generation callback context */
14137
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
14138
{
14139
    if (ssl)
14140
        ssl->GenMasterCtx = ctx;
14141
}
14142
/* Get master secret generation callback context */
14143
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
14144
{
14145
    if (ssl)
14146
        return ssl->GenMasterCtx;
14147
14148
    return NULL;
14149
}
14150
14151
/* callback for extended master secret generation */
14152
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
14153
    CallbackGenExtMasterSecret cb)
14154
{
14155
    if (ctx)
14156
        ctx->GenExtMasterCb = cb;
14157
}
14158
/* Set extended master secret generation callback context */
14159
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
14160
{
14161
    if (ssl)
14162
        ssl->GenExtMasterCtx = ctx;
14163
}
14164
/* Get extended master secret generation callback context */
14165
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
14166
{
14167
    if (ssl)
14168
        return ssl->GenExtMasterCtx;
14169
14170
    return NULL;
14171
}
14172
14173
14174
/* callback for session key generation */
14175
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
14176
{
14177
    if (ctx)
14178
        ctx->GenSessionKeyCb = cb;
14179
}
14180
/* Set session key generation callback context */
14181
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
14182
{
14183
    if (ssl)
14184
        ssl->GenSessionKeyCtx = ctx;
14185
}
14186
/* Get session key generation callback context */
14187
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
14188
{
14189
    if (ssl)
14190
        return ssl->GenSessionKeyCtx;
14191
14192
    return NULL;
14193
}
14194
14195
/* callback for setting encryption keys */
14196
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
14197
{
14198
    if (ctx)
14199
        ctx->EncryptKeysCb = cb;
14200
}
14201
/* Set encryption keys callback context */
14202
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
14203
{
14204
    if (ssl)
14205
        ssl->EncryptKeysCtx = ctx;
14206
}
14207
/* Get encryption keys callback context */
14208
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
14209
{
14210
    if (ssl)
14211
        return ssl->EncryptKeysCtx;
14212
14213
    return NULL;
14214
}
14215
14216
/* callback for Tls finished */
14217
/* the callback can be used to build TLS Finished message if enabled */
14218
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
14219
{
14220
    if (ctx)
14221
        ctx->TlsFinishedCb = cb;
14222
}
14223
/* Set Tls finished callback context */
14224
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
14225
{
14226
    if (ssl)
14227
        ssl->TlsFinishedCtx = ctx;
14228
}
14229
/* Get Tls finished callback context */
14230
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
14231
{
14232
    if (ssl)
14233
        return ssl->TlsFinishedCtx;
14234
14235
    return NULL;
14236
}
14237
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
14238
/* callback for verify data */
14239
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
14240
{
14241
    if (ctx)
14242
        ctx->VerifyMacCb = cb;
14243
}
14244
14245
/* Set set keys callback context */
14246
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
14247
{
14248
    if (ssl)
14249
        ssl->VerifyMacCtx = ctx;
14250
}
14251
/* Get set  keys callback context */
14252
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
14253
{
14254
    if (ssl)
14255
        return ssl->VerifyMacCtx;
14256
14257
    return NULL;
14258
}
14259
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
14260
14261
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
14262
                                      CallbackHKDFExpandLabel cb)
14263
{
14264
    if (ctx)
14265
        ctx->HKDFExpandLabelCb = cb;
14266
}
14267
#ifdef WOLFSSL_PUBLIC_ASN
14268
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
14269
                                        CallbackProcessPeerCert cb)
14270
{
14271
    if (ctx)
14272
        ctx->ProcessPeerCertCb = cb;
14273
}
14274
#endif /* WOLFSSL_PUBLIC_ASN */
14275
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
14276
                                       CallbackProcessServerSigKex cb)
14277
{
14278
    if (ctx)
14279
        ctx->ProcessServerSigKexCb = cb;
14280
}
14281
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
14282
                                          CallbackPerformTlsRecordProcessing cb)
14283
{
14284
    if (ctx)
14285
        ctx->PerformTlsRecordProcessingCb = cb;
14286
}
14287
#endif /* HAVE_PK_CALLBACKS */
14288
#endif /* NO_CERTS */
14289
14290
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
14291
14292
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
14293
{
14294
    if (ctx)
14295
        ctx->HkdfExtractCb = cb;
14296
}
14297
14298
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
14299
{
14300
    if (ssl)
14301
        ssl->HkdfExtractCtx = ctx;
14302
}
14303
14304
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
14305
{
14306
    if (ssl)
14307
        return ssl->HkdfExtractCtx;
14308
14309
    return NULL;
14310
}
14311
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
14312
14313
#ifdef WOLFSSL_HAVE_WOLFSCEP
14314
    /* Used by autoconf to see if wolfSCEP is available */
14315
    void wolfSSL_wolfSCEP(void) {}
14316
#endif
14317
14318
14319
#ifdef WOLFSSL_HAVE_CERT_SERVICE
14320
    /* Used by autoconf to see if cert service is available */
14321
    void wolfSSL_cert_service(void) {}
14322
#endif
14323
14324
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
14325
    !defined(WOLFCRYPT_ONLY)
14326
14327
    /* NID variables are dependent on compatibility header files currently
14328
     *
14329
     * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL
14330
     *         on fail
14331
     */
14332
14333
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id)
14334
    {
14335
        return wolfSSL_OBJ_nid2obj_ex(id, NULL);
14336
    }
14337
14338
14339
    WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id,
14340
                                                WOLFSSL_ASN1_OBJECT* arg_obj)
14341
    {
14342
        word32 oidSz = 0;
14343
        int nid = 0;
14344
        const byte* oid;
14345
        word32 type = 0;
14346
        WOLFSSL_ASN1_OBJECT* obj = arg_obj;
14347
        byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */
14348
        word32 objSz = 0;
14349
        const char* sName = NULL;
14350
        int i;
14351
14352
#ifdef WOLFSSL_DEBUG_OPENSSL
14353
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj");
14354
#endif
14355
14356
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
14357
            if (wolfssl_object_info[i].nid == id) {
14358
                nid = id;
14359
                id = wolfssl_object_info[i].id;
14360
                sName = wolfssl_object_info[i].sName;
14361
                type = wolfssl_object_info[i].type;
14362
                break;
14363
            }
14364
        }
14365
        if (i == (int)WOLFSSL_OBJECT_INFO_SZ) {
14366
            WOLFSSL_MSG("NID not in table");
14367
        #ifdef WOLFSSL_QT
14368
            sName = NULL;
14369
            type = (word32)id;
14370
        #else
14371
            return NULL;
14372
        #endif
14373
        }
14374
14375
    #ifdef HAVE_ECC
14376
         if (type == 0 && wc_ecc_get_oid((word32)id, &oid, &oidSz) > 0) {
14377
             type = oidCurveType;
14378
         }
14379
    #endif /* HAVE_ECC */
14380
14381
        if (sName != NULL) {
14382
            if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) {
14383
                WOLFSSL_MSG("Attempted short name is too large");
14384
                return NULL;
14385
            }
14386
        }
14387
14388
        oid = OidFromId((word32)id, type, &oidSz);
14389
14390
        /* set object ID to buffer */
14391
        if (obj == NULL){
14392
            obj = wolfSSL_ASN1_OBJECT_new();
14393
            if (obj == NULL) {
14394
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
14395
                return NULL;
14396
            }
14397
        }
14398
        obj->nid     = nid;
14399
        obj->type    = id;
14400
        obj->grp     = (int)type;
14401
14402
        obj->sName[0] = '\0';
14403
        if (sName != NULL) {
14404
            XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName));
14405
        }
14406
14407
        objBuf[0] = ASN_OBJECT_ID; objSz++;
14408
        objSz += SetLength(oidSz, objBuf + 1);
14409
        if (oidSz) {
14410
            XMEMCPY(objBuf + objSz, oid, oidSz);
14411
            objSz     += oidSz;
14412
        }
14413
14414
        if (obj->objSz == 0 || objSz != obj->objSz) {
14415
            obj->objSz = objSz;
14416
            if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) ||
14417
                                                           (obj->obj == NULL)) {
14418
                if (obj->obj != NULL)
14419
                    XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1);
14420
                obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
14421
                if (obj->obj == NULL) {
14422
                    wolfSSL_ASN1_OBJECT_free(obj);
14423
                    return NULL;
14424
                }
14425
                obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
14426
            }
14427
            else {
14428
                obj->dynamic &= (unsigned char)~WOLFSSL_ASN1_DYNAMIC_DATA;
14429
            }
14430
        }
14431
        XMEMCPY((byte*)obj->obj, objBuf, obj->objSz);
14432
14433
        (void)type;
14434
14435
        return obj;
14436
    }
14437
14438
    static const char* oid_translate_num_to_str(const char* oid)
14439
    {
14440
        const struct oid_dict {
14441
            const char* num;
14442
            const char* desc;
14443
        } oid_dict[] = {
14444
            { "2.5.29.37.0",       "Any Extended Key Usage" },
14445
            { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" },
14446
            { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" },
14447
            { "1.3.6.1.5.5.7.3.3", "Code Signing" },
14448
            { "1.3.6.1.5.5.7.3.4", "E-mail Protection" },
14449
            { "1.3.6.1.5.5.7.3.8", "Time Stamping" },
14450
            { "1.3.6.1.5.5.7.3.9", "OCSP Signing" },
14451
            { NULL, NULL }
14452
        };
14453
        const struct oid_dict* idx;
14454
14455
        for (idx = oid_dict; idx->num != NULL; idx++) {
14456
            if (!XSTRCMP(oid, idx->num)) {
14457
                return idx->desc;
14458
            }
14459
        }
14460
        return NULL;
14461
    }
14462
14463
    static int wolfssl_obj2txt_numeric(char *buf, int bufLen,
14464
                                       const WOLFSSL_ASN1_OBJECT *a)
14465
    {
14466
        int bufSz;
14467
        int    length;
14468
        word32 idx = 0;
14469
        byte   tag;
14470
14471
        if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) {
14472
            return WOLFSSL_FAILURE;
14473
        }
14474
14475
        if (tag != ASN_OBJECT_ID) {
14476
            WOLFSSL_MSG("Bad ASN1 Object");
14477
            return WOLFSSL_FAILURE;
14478
        }
14479
14480
        if (GetLength((const byte*)a->obj, &idx, &length,
14481
                       a->objSz) < 0 || length < 0) {
14482
            return ASN_PARSE_E;
14483
        }
14484
14485
        if (bufLen < MAX_OID_STRING_SZ) {
14486
            bufSz = bufLen - 1;
14487
        }
14488
        else {
14489
            bufSz = MAX_OID_STRING_SZ;
14490
        }
14491
14492
        if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx,
14493
                    (word32)length)) <= 0) {
14494
            WOLFSSL_MSG("Error decoding OID");
14495
            return WOLFSSL_FAILURE;
14496
        }
14497
14498
        buf[bufSz] = '\0';
14499
14500
        return bufSz;
14501
    }
14502
14503
    /* If no_name is one then use numerical form, otherwise short name.
14504
     *
14505
     * Returns the buffer size on success, WOLFSSL_FAILURE on error
14506
     */
14507
    int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a,
14508
                            int no_name)
14509
    {
14510
        int bufSz;
14511
        const char* desc;
14512
        const char* name;
14513
14514
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt");
14515
14516
        if (buf == NULL || bufLen <= 1 || a == NULL) {
14517
            WOLFSSL_MSG("Bad input argument");
14518
            return WOLFSSL_FAILURE;
14519
        }
14520
14521
        if (no_name == 1) {
14522
            return wolfssl_obj2txt_numeric(buf, bufLen, a);
14523
        }
14524
14525
        /* return long name unless using x509small, then return short name */
14526
#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA)
14527
        name = a->sName;
14528
#else
14529
        name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a));
14530
#endif
14531
14532
        if (name == NULL) {
14533
            WOLFSSL_MSG("Name not found");
14534
            bufSz = 0;
14535
        }
14536
        else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) {
14537
            bufSz = (int)XSTRLEN(name);
14538
        }
14539
        else {
14540
            bufSz = bufLen - 1;
14541
        }
14542
        if (bufSz) {
14543
            XMEMCPY(buf, name, (size_t)bufSz);
14544
        }
14545
        else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL ||
14546
                 a->type == WOLFSSL_GEN_URI) {
14547
            bufSz = (int)XSTRLEN((const char*)a->obj);
14548
            XMEMCPY(buf, a->obj, min((word32)bufSz, (word32)bufLen));
14549
        }
14550
        else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) {
14551
            if ((desc = oid_translate_num_to_str(buf))) {
14552
                bufSz = (int)XSTRLEN(desc);
14553
                bufSz = (int)min((word32)bufSz,(word32) bufLen - 1);
14554
                XMEMCPY(buf, desc, (size_t)bufSz);
14555
            }
14556
        }
14557
        else {
14558
            bufSz = 0;
14559
        }
14560
14561
        buf[bufSz] = '\0';
14562
14563
        return bufSz;
14564
    }
14565
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
14566
14567
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
14568
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
14569
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
14570
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL)
14571
    /* Returns the long name that corresponds with an ASN1_OBJECT nid value.
14572
     *  n : NID value of ASN1_OBJECT to search */
14573
    const char* wolfSSL_OBJ_nid2ln(int n)
14574
    {
14575
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
14576
        size_t i;
14577
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln");
14578
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
14579
            if (obj_info->nid == n) {
14580
                return obj_info->lName;
14581
            }
14582
        }
14583
        WOLFSSL_MSG("NID not found in table");
14584
        return NULL;
14585
    }
14586
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
14587
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */
14588
14589
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
14590
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
14591
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
14592
    defined(WOLFSSL_HAPROXY)
14593
    /* Return the corresponding short name for the nid <n>.
14594
     * or NULL if short name can't be found.
14595
     */
14596
    const char * wolfSSL_OBJ_nid2sn(int n) {
14597
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
14598
        size_t i;
14599
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn");
14600
14601
        if (n == WC_NID_md5) {
14602
            /* WC_NID_surname == WC_NID_md5 and WC_NID_surname comes before WC_NID_md5 in
14603
             * wolfssl_object_info. As a result, the loop below will incorrectly
14604
             * return "SN" instead of "MD5." WC_NID_surname isn't the true OpenSSL
14605
             * NID, but other functions rely on this table and modifying it to
14606
             * conform with OpenSSL's NIDs isn't trivial. */
14607
             return "MD5";
14608
        }
14609
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
14610
            if (obj_info->nid == n) {
14611
                return obj_info->sName;
14612
            }
14613
        }
14614
        WOLFSSL_MSG_EX("SN not found (nid:%d)",n);
14615
        return NULL;
14616
    }
14617
14618
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
14619
    int wolfSSL_OBJ_sn2nid(const char *sn) {
14620
        WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid");
14621
        if (sn == NULL)
14622
            return WC_NID_undef;
14623
        return wc_OBJ_sn2nid(sn);
14624
    }
14625
#endif
14626
14627
    size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o)
14628
    {
14629
        size_t ret = 0;
14630
        int err = 0;
14631
        word32 idx = 0;
14632
        int len = 0;
14633
14634
        WOLFSSL_ENTER("wolfSSL_OBJ_length");
14635
14636
        if (o == NULL || o->obj == NULL) {
14637
            WOLFSSL_MSG("Bad argument.");
14638
            err = 1;
14639
        }
14640
14641
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
14642
            WOLFSSL_MSG("Error parsing ASN.1 header.");
14643
            err = 1;
14644
        }
14645
        if (err == 0) {
14646
            ret = (size_t)len;
14647
        }
14648
14649
        WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret);
14650
14651
        return ret;
14652
    }
14653
14654
    const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o)
14655
    {
14656
        const unsigned char* ret = NULL;
14657
        int err = 0;
14658
        word32 idx = 0;
14659
        int len = 0;
14660
14661
        WOLFSSL_ENTER("wolfSSL_OBJ_get0_data");
14662
14663
        if (o == NULL || o->obj == NULL) {
14664
            WOLFSSL_MSG("Bad argument.");
14665
            err = 1;
14666
        }
14667
14668
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
14669
            WOLFSSL_MSG("Error parsing ASN.1 header.");
14670
            err = 1;
14671
        }
14672
        if (err == 0) {
14673
            ret = o->obj + idx;
14674
        }
14675
14676
        return ret;
14677
    }
14678
14679
14680
    /* Gets the NID value that corresponds with the ASN1 object.
14681
     *
14682
     * o ASN1 object to get NID of
14683
     *
14684
     * Return NID on success and a negative value on failure
14685
     */
14686
    int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o)
14687
    {
14688
        word32 oid = 0;
14689
        word32 idx = 0;
14690
        int ret;
14691
14692
#ifdef WOLFSSL_DEBUG_OPENSSL
14693
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid");
14694
#endif
14695
14696
        if (o == NULL) {
14697
            return WOLFSSL_FATAL_ERROR;
14698
        }
14699
14700
        #ifdef WOLFSSL_QT
14701
        if (o->grp == oidCertExtType) {
14702
            /* If nid is an unknown extension, return WC_NID_undef */
14703
            if (wolfSSL_OBJ_nid2sn(o->nid) == NULL)
14704
                return WC_NID_undef;
14705
        }
14706
        #endif
14707
14708
        if (o->nid > 0)
14709
            return o->nid;
14710
        if ((ret = GetObjectId(o->obj, &idx, &oid,
14711
                                    (word32)o->grp, o->objSz)) < 0) {
14712
            if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) {
14713
                /* Put ASN object tag in front and try again */
14714
                int len = SetObjectId((int)o->objSz, NULL) + (int)o->objSz;
14715
                byte* buf = (byte*)XMALLOC((size_t)len, NULL,
14716
                                            DYNAMIC_TYPE_TMP_BUFFER);
14717
                if (!buf) {
14718
                    WOLFSSL_MSG("malloc error");
14719
                    return WOLFSSL_FATAL_ERROR;
14720
                }
14721
                idx = (word32)SetObjectId((int)o->objSz, buf);
14722
                XMEMCPY(buf + idx, o->obj, o->objSz);
14723
                idx = 0;
14724
                ret = GetObjectId(buf, &idx, &oid, (word32)o->grp, (word32)len);
14725
                XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
14726
                if (ret < 0) {
14727
                    WOLFSSL_MSG("Issue getting OID of object");
14728
                    return WOLFSSL_FATAL_ERROR;
14729
                }
14730
            }
14731
            else {
14732
                WOLFSSL_MSG("Issue getting OID of object");
14733
                return WOLFSSL_FATAL_ERROR;
14734
            }
14735
        }
14736
14737
        return oid2nid(oid, o->grp);
14738
    }
14739
14740
    /* Return the corresponding NID for the long name <ln>
14741
     * or WC_NID_undef if NID can't be found.
14742
     */
14743
    int wolfSSL_OBJ_ln2nid(const char *ln)
14744
    {
14745
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
14746
        size_t lnlen;
14747
        WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid");
14748
        if (ln && (lnlen = XSTRLEN(ln)) > 0) {
14749
            /* Accept input like "/commonName=" */
14750
            if (ln[0] == '/') {
14751
                ln++;
14752
                lnlen--;
14753
            }
14754
            if (lnlen) {
14755
                size_t i;
14756
14757
                if (ln[lnlen-1] == '=') {
14758
                    lnlen--;
14759
                }
14760
                for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
14761
                    if (lnlen == XSTRLEN(obj_info->lName) &&
14762
                            XSTRNCMP(ln, obj_info->lName, lnlen) == 0) {
14763
                        return obj_info->nid;
14764
                    }
14765
                }
14766
            }
14767
        }
14768
        return WC_NID_undef;
14769
    }
14770
14771
    /* compares two objects, return 0 if equal */
14772
    int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a,
14773
                        const WOLFSSL_ASN1_OBJECT* b)
14774
    {
14775
        WOLFSSL_ENTER("wolfSSL_OBJ_cmp");
14776
14777
        if (a && b && a->obj && b->obj) {
14778
            if (a->objSz == b->objSz) {
14779
                return XMEMCMP(a->obj, b->obj, a->objSz);
14780
            }
14781
            else if (a->type == EXT_KEY_USAGE_OID ||
14782
                     b->type == EXT_KEY_USAGE_OID) {
14783
                /* Special case for EXT_KEY_USAGE_OID so that
14784
                 * cmp will be treated as a substring search */
14785
                /* Used in libest to check for id-kp-cmcRA in
14786
                 * EXT_KEY_USAGE extension */
14787
                unsigned int idx;
14788
                const byte* s; /* shorter */
14789
                unsigned int sLen;
14790
                const byte* l; /* longer */
14791
                unsigned int lLen;
14792
                if (a->objSz > b->objSz) {
14793
                    s = b->obj; sLen = b->objSz;
14794
                    l = a->obj; lLen = a->objSz;
14795
                }
14796
                else {
14797
                    s = a->obj; sLen = a->objSz;
14798
                    l = b->obj; lLen = b->objSz;
14799
                }
14800
                for (idx = 0; idx <= lLen - sLen; idx++) {
14801
                    if (XMEMCMP(l + idx, s, sLen) == 0) {
14802
                        /* Found substring */
14803
                        return 0;
14804
                    }
14805
                }
14806
            }
14807
        }
14808
14809
        return WOLFSSL_FATAL_ERROR;
14810
    }
14811
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
14812
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */
14813
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
14814
    defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
14815
    defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
14816
    defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
14817
    /* Gets the NID value that is related to the OID string passed in. Example
14818
     * string would be "2.5.29.14" for subject key ID.
14819
     *
14820
     * returns NID value on success and WC_NID_undef on error
14821
     */
14822
    int wolfSSL_OBJ_txt2nid(const char* s)
14823
    {
14824
        unsigned int i;
14825
    #ifdef WOLFSSL_CERT_EXT
14826
        int ret;
14827
        unsigned int sum = 0;
14828
        unsigned int outSz = MAX_OID_SZ;
14829
        unsigned char out[MAX_OID_SZ];
14830
14831
        XMEMSET(out, 0, sizeof(out));
14832
    #endif
14833
14834
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid");
14835
14836
        if (s == NULL) {
14837
            return WC_NID_undef;
14838
        }
14839
14840
    #ifdef WOLFSSL_CERT_EXT
14841
        ret = EncodePolicyOID(out, &outSz, s, NULL);
14842
        if (ret == 0) {
14843
            /* sum OID */
14844
            sum = wc_oid_sum(out, outSz);
14845
        }
14846
    #endif /* WOLFSSL_CERT_EXT */
14847
14848
        /* get the group that the OID's sum is in
14849
         * @TODO possible conflict with multiples */
14850
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
14851
            int len;
14852
        #ifdef WOLFSSL_CERT_EXT
14853
            if (ret == 0) {
14854
                if (wolfssl_object_info[i].id == (int)sum) {
14855
                    return wolfssl_object_info[i].nid;
14856
                }
14857
            }
14858
        #endif
14859
14860
            /* try as a short name */
14861
            len = (int)XSTRLEN(s);
14862
            if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len &&
14863
                XSTRNCMP(wolfssl_object_info[i].sName, s, (word32)len) == 0) {
14864
                return wolfssl_object_info[i].nid;
14865
            }
14866
14867
            /* try as a long name */
14868
            if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len &&
14869
                XSTRNCMP(wolfssl_object_info[i].lName, s, (word32)len) == 0) {
14870
                return wolfssl_object_info[i].nid;
14871
            }
14872
        }
14873
14874
        return WC_NID_undef;
14875
    }
14876
#endif
14877
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
14878
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
14879
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
14880
    defined(WOLFSSL_HAPROXY)
14881
14882
    /* Creates new ASN1_OBJECT from short name, long name, or text
14883
     * representation of oid. If no_name is 0, then short name, long name, and
14884
     * numerical value of oid are interpreted. If no_name is 1, then only the
14885
     * numerical value of the oid is interpreted.
14886
     *
14887
     * Returns pointer to ASN1_OBJECT on success, or NULL on error.
14888
     */
14889
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
14890
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name)
14891
    {
14892
        int i, ret;
14893
        int nid = WC_NID_undef;
14894
        unsigned int outSz = MAX_OID_SZ;
14895
        unsigned char out[MAX_OID_SZ];
14896
        WOLFSSL_ASN1_OBJECT* obj;
14897
14898
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj");
14899
14900
        if (s == NULL)
14901
            return NULL;
14902
14903
        /* If s is numerical value, try to sum oid */
14904
        ret = EncodePolicyOID(out, &outSz, s, NULL);
14905
        if (ret == 0 && outSz > 0) {
14906
            /* If numerical encode succeeded then just
14907
             * create object from that because sums are
14908
             * not unique and can cause confusion. */
14909
            obj = wolfSSL_ASN1_OBJECT_new();
14910
            if (obj == NULL) {
14911
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
14912
                return NULL;
14913
            }
14914
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
14915
            obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL,
14916
                    DYNAMIC_TYPE_ASN1);
14917
            if (obj->obj == NULL) {
14918
                wolfSSL_ASN1_OBJECT_free(obj);
14919
                return NULL;
14920
            }
14921
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
14922
            i = SetObjectId((int)outSz, (byte*)obj->obj);
14923
            XMEMCPY((byte*)obj->obj + i, out, outSz);
14924
            obj->objSz = (word32)i + outSz;
14925
            return obj;
14926
        }
14927
14928
        /* TODO: update short names in wolfssl_object_info and check OID sums
14929
           are correct */
14930
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
14931
            /* Short name, long name, and numerical value are interpreted */
14932
            if (no_name == 0 &&
14933
                ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) ||
14934
                 (XSTRCMP(s, wolfssl_object_info[i].lName) == 0)))
14935
            {
14936
                    nid = wolfssl_object_info[i].nid;
14937
            }
14938
        }
14939
14940
        if (nid != WC_NID_undef)
14941
            return wolfSSL_OBJ_nid2obj(nid);
14942
14943
        return NULL;
14944
    }
14945
#endif
14946
14947
    /* compatibility function. Its intended use is to remove OID's from an
14948
     * internal table that have been added with OBJ_create. wolfSSL manages its
14949
     * own internal OID values and does not currently support OBJ_create. */
14950
    void wolfSSL_OBJ_cleanup(void)
14951
    {
14952
        WOLFSSL_ENTER("wolfSSL_OBJ_cleanup");
14953
    }
14954
14955
    #ifndef NO_WOLFSSL_STUB
14956
    int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln)
14957
    {
14958
        (void)oid;
14959
        (void)sn;
14960
        (void)ln;
14961
        WOLFSSL_STUB("wolfSSL_OBJ_create");
14962
        return WOLFSSL_FAILURE;
14963
    }
14964
    #endif
14965
14966
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
14967
    {
14968
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
14969
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
14970
        ssl->options.verifyDepth = (byte)depth;
14971
    #endif
14972
    }
14973
14974
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
14975
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
14976
14977
#ifdef OPENSSL_EXTRA
14978
14979
/* wolfSSL uses negative values for error states. This function returns an
14980
 * unsigned type so the value returned is the absolute value of the error.
14981
 */
14982
unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line)
14983
{
14984
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
14985
14986
    (void)line;
14987
    (void)file;
14988
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
14989
    {
14990
        int ret;
14991
14992
        if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) {
14993
            WOLFSSL_MSG("Issue peeking at error node in queue");
14994
            return 0;
14995
        }
14996
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \
14997
        || defined(WOLFSSL_HAPROXY)
14998
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
14999
            return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
15000
    #endif
15001
    #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
15002
        if (ret == ASN1_R_HEADER_TOO_LONG) {
15003
            return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
15004
        }
15005
    #endif
15006
        return (unsigned long)ret;
15007
    }
15008
#else
15009
    return (unsigned long)(0 - NOT_COMPILED_IN);
15010
#endif
15011
}
15012
15013
#endif /* OPENSSL_EXTRA */
15014
15015
#ifdef HAVE_EX_DATA_CRYPTO
15016
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
15017
15018
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
15019
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
15020
        WOLFSSL_CRYPTO_EX_free* free_func)
15021
{
15022
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
15023
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
15024
    if (new_ctx == NULL)
15025
        return WOLFSSL_FATAL_ERROR;
15026
    new_ctx->ctx_l = ctx_l;
15027
    new_ctx->ctx_ptr = ctx_ptr;
15028
    new_ctx->new_func = new_func;
15029
    new_ctx->free_func = free_func;
15030
    new_ctx->dup_func = dup_func;
15031
    new_ctx->next = NULL;
15032
    /* Push to end of list */
15033
    while (*dst != NULL)
15034
        dst = &(*dst)->next;
15035
    *dst = new_ctx;
15036
    return 0;
15037
}
15038
15039
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
15040
{
15041
    while (cb_ctx != NULL) {
15042
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
15043
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
15044
        cb_ctx = next;
15045
    }
15046
}
15047
15048
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
15049
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
15050
{
15051
    int idx = 0;
15052
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
15053
        if (cb_ctx->new_func != NULL)
15054
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
15055
                    cb_ctx->ctx_ptr);
15056
    }
15057
}
15058
15059
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
15060
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
15061
{
15062
    int idx = 0;
15063
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
15064
        if (cb_ctx->dup_func != NULL) {
15065
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
15066
            if (!cb_ctx->dup_func(out, in,
15067
                    &ptr, idx,
15068
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
15069
                return WOLFSSL_FAILURE;
15070
            }
15071
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
15072
        }
15073
    }
15074
    return WOLFSSL_SUCCESS;
15075
}
15076
15077
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
15078
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
15079
{
15080
    int idx = 0;
15081
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
15082
        if (cb_ctx->free_func != NULL)
15083
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
15084
                    cb_ctx->ctx_ptr);
15085
    }
15086
}
15087
15088
/**
15089
 * get_ex_new_index is a helper function for the following
15090
 * xx_get_ex_new_index functions:
15091
 *  - wolfSSL_CRYPTO_get_ex_new_index
15092
 *  - wolfSSL_CTX_get_ex_new_index
15093
 *  - wolfSSL_get_ex_new_index
15094
 * Issues a unique index number for the specified class-index.
15095
 * Returns an index number greater or equal to zero on success,
15096
 * -1 on failure.
15097
 */
15098
int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
15099
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
15100
        WOLFSSL_CRYPTO_EX_free* free_func)
15101
{
15102
    /* index counter for each class index*/
15103
    static int ctx_idx = 0;
15104
    static int ssl_idx = 0;
15105
    static int ssl_session_idx = 0;
15106
    static int x509_idx = 0;
15107
15108
    int idx = -1;
15109
15110
    switch(class_index) {
15111
        case WOLF_CRYPTO_EX_INDEX_SSL:
15112
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
15113
                    dup_func, free_func);
15114
            idx = ssl_idx++;
15115
            break;
15116
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
15117
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
15118
                    dup_func, free_func);
15119
            idx = ctx_idx++;
15120
            break;
15121
        case WOLF_CRYPTO_EX_INDEX_X509:
15122
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
15123
                    dup_func, free_func);
15124
            idx = x509_idx++;
15125
            break;
15126
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
15127
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
15128
                    new_func, dup_func, free_func) != 0)
15129
                return WOLFSSL_FATAL_ERROR;
15130
            idx = ssl_session_idx++;
15131
            break;
15132
15133
        /* following class indexes are not supoprted */
15134
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
15135
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
15136
        case WOLF_CRYPTO_EX_INDEX_DH:
15137
        case WOLF_CRYPTO_EX_INDEX_DSA:
15138
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
15139
        case WOLF_CRYPTO_EX_INDEX_RSA:
15140
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
15141
        case WOLF_CRYPTO_EX_INDEX_UI:
15142
        case WOLF_CRYPTO_EX_INDEX_BIO:
15143
        case WOLF_CRYPTO_EX_INDEX_APP:
15144
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
15145
        case WOLF_CRYPTO_EX_INDEX_DRBG:
15146
        default:
15147
            break;
15148
    }
15149
    if (idx >= MAX_EX_DATA)
15150
        return WOLFSSL_FATAL_ERROR;
15151
    return idx;
15152
}
15153
#endif /* HAVE_EX_DATA_CRYPTO */
15154
15155
#ifdef HAVE_EX_DATA_CRYPTO
15156
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
15157
                                 WOLFSSL_CRYPTO_EX_new* new_func,
15158
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
15159
                                 WOLFSSL_CRYPTO_EX_free* free_func)
15160
{
15161
15162
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
15163
15164
    return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx, arg,
15165
                                    new_func, dup_func, free_func);
15166
}
15167
15168
/* Return the index that can be used for the WOLFSSL structure to store
15169
 * application data.
15170
 *
15171
 */
15172
int wolfSSL_get_ex_new_index(long argValue, void* arg,
15173
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
15174
        WOLFSSL_CRYPTO_EX_free* cb3)
15175
{
15176
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
15177
15178
    return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue, arg,
15179
            cb1, cb2, cb3);
15180
}
15181
#endif /* HAVE_EX_DATA_CRYPTO */
15182
15183
#ifdef OPENSSL_EXTRA
15184
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
15185
{
15186
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
15187
#ifdef HAVE_EX_DATA
15188
    if (ctx != NULL) {
15189
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
15190
    }
15191
#else
15192
    (void)ctx;
15193
    (void)idx;
15194
#endif
15195
    return NULL;
15196
}
15197
15198
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
15199
{
15200
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
15201
#ifdef HAVE_EX_DATA
15202
    if (ctx != NULL) {
15203
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
15204
    }
15205
#else
15206
    (void)ctx;
15207
    (void)idx;
15208
    (void)data;
15209
#endif
15210
    return WOLFSSL_FAILURE;
15211
}
15212
15213
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15214
int wolfSSL_CTX_set_ex_data_with_cleanup(
15215
    WOLFSSL_CTX* ctx,
15216
    int idx,
15217
    void* data,
15218
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
15219
{
15220
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
15221
    if (ctx != NULL) {
15222
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
15223
                                                       cleanup_routine);
15224
    }
15225
    return WOLFSSL_FAILURE;
15226
}
15227
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
15228
#endif /* OPENSSL_EXTRA */
15229
15230
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
15231
15232
/* Returns char* to app data stored in ex[0].
15233
 *
15234
 * ssl WOLFSSL structure to get app data from
15235
 */
15236
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
15237
{
15238
    /* checkout exdata stuff... */
15239
    WOLFSSL_ENTER("wolfSSL_get_app_data");
15240
15241
    return wolfSSL_get_ex_data(ssl, 0);
15242
}
15243
15244
15245
/* Set ex array 0 to have app data
15246
 *
15247
 * ssl WOLFSSL struct to set app data in
15248
 * arg data to be stored
15249
 *
15250
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
15251
 */
15252
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
15253
    WOLFSSL_ENTER("wolfSSL_set_app_data");
15254
15255
    return wolfSSL_set_ex_data(ssl, 0, arg);
15256
}
15257
15258
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
15259
15260
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
15261
0
{
15262
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
15263
#ifdef HAVE_EX_DATA
15264
    if (ssl != NULL) {
15265
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
15266
    }
15267
#else
15268
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
15269
0
    (void)ssl;
15270
0
    (void)idx;
15271
0
    (void)data;
15272
0
#endif
15273
0
    return WOLFSSL_FAILURE;
15274
0
}
15275
15276
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
15277
int wolfSSL_set_ex_data_with_cleanup(
15278
    WOLFSSL* ssl,
15279
    int idx,
15280
    void* data,
15281
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
15282
{
15283
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
15284
    if (ssl != NULL)
15285
    {
15286
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
15287
                                                       cleanup_routine);
15288
    }
15289
    return WOLFSSL_FAILURE;
15290
}
15291
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
15292
15293
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
15294
0
{
15295
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
15296
#ifdef HAVE_EX_DATA
15297
    if (ssl != NULL) {
15298
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
15299
    }
15300
#else
15301
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
15302
0
    (void)ssl;
15303
0
    (void)idx;
15304
0
#endif
15305
0
    return 0;
15306
0
}
15307
15308
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
15309
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
15310
15311
/* returns the enum value associated with handshake state
15312
 *
15313
 * ssl the WOLFSSL structure to get state of
15314
 */
15315
int wolfSSL_get_state(const WOLFSSL* ssl)
15316
{
15317
    WOLFSSL_ENTER("wolfSSL_get_state");
15318
15319
    if (ssl == NULL) {
15320
        WOLFSSL_MSG("Null argument passed in");
15321
        return WOLFSSL_FAILURE;
15322
    }
15323
15324
    return ssl->options.handShakeState;
15325
}
15326
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
15327
15328
#ifdef OPENSSL_EXTRA
15329
void wolfSSL_certs_clear(WOLFSSL* ssl)
15330
{
15331
    WOLFSSL_ENTER("wolfSSL_certs_clear");
15332
15333
    if (ssl == NULL)
15334
        return;
15335
15336
    /* ctx still owns certificate, certChain, key, dh, and cm */
15337
    if (ssl->buffers.weOwnCert) {
15338
        FreeDer(&ssl->buffers.certificate);
15339
        ssl->buffers.weOwnCert = 0;
15340
    }
15341
    ssl->buffers.certificate = NULL;
15342
    if (ssl->buffers.weOwnCertChain) {
15343
        FreeDer(&ssl->buffers.certChain);
15344
        ssl->buffers.weOwnCertChain = 0;
15345
    }
15346
    ssl->buffers.certChain = NULL;
15347
#ifdef WOLFSSL_TLS13
15348
    ssl->buffers.certChainCnt = 0;
15349
#endif
15350
    if (ssl->buffers.weOwnKey) {
15351
        FreeDer(&ssl->buffers.key);
15352
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
15353
        FreeDer(&ssl->buffers.keyMask);
15354
    #endif
15355
        ssl->buffers.weOwnKey = 0;
15356
    }
15357
    ssl->buffers.key      = NULL;
15358
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
15359
    ssl->buffers.keyMask  = NULL;
15360
#endif
15361
    ssl->buffers.keyType  = 0;
15362
    ssl->buffers.keyId    = 0;
15363
    ssl->buffers.keyLabel = 0;
15364
    ssl->buffers.keySz    = 0;
15365
    ssl->buffers.keyDevId = 0;
15366
#ifdef WOLFSSL_DUAL_ALG_CERTS
15367
    if (ssl->buffers.weOwnAltKey) {
15368
        FreeDer(&ssl->buffers.altKey);
15369
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
15370
        FreeDer(&ssl->buffers.altKeyMask);
15371
    #endif
15372
        ssl->buffers.weOwnAltKey = 0;
15373
    }
15374
    ssl->buffers.altKey     = NULL;
15375
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
15376
    ssl->buffers.altKeyMask = NULL;
15377
#endif
15378
#endif /* WOLFSSL_DUAL_ALG_CERTS */
15379
}
15380
#endif
15381
15382
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
15383
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
15384
15385
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
15386
{
15387
    WOLFSSL_ENTER("wolfSSL_ctrl");
15388
    if (ssl == NULL)
15389
        return BAD_FUNC_ARG;
15390
15391
    switch (cmd) {
15392
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
15393
            defined(OPENSSL_ALL)
15394
        #ifdef HAVE_SNI
15395
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
15396
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
15397
            if (pt == NULL) {
15398
                WOLFSSL_MSG("Passed in NULL Host Name.");
15399
                break;
15400
            }
15401
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
15402
        #endif /* HAVE_SNI */
15403
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
15404
        default:
15405
            WOLFSSL_MSG("Case not implemented.");
15406
    }
15407
    (void)opt;
15408
    (void)pt;
15409
    return WOLFSSL_FAILURE;
15410
}
15411
15412
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
15413
{
15414
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
15415
    long ctrl_opt;
15416
#endif
15417
    long ret = WOLFSSL_SUCCESS;
15418
15419
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
15420
    if (ctx == NULL)
15421
        return WOLFSSL_FAILURE;
15422
15423
    switch (cmd) {
15424
    case SSL_CTRL_CHAIN:
15425
#ifdef SESSION_CERTS
15426
    {
15427
        /*
15428
         * We don't care about opt here because a copy of the certificate is
15429
         * stored anyway so increasing the reference counter is not necessary.
15430
         * Just check to make sure that it is set to one of the correct values.
15431
         */
15432
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
15433
        WOLFSSL_X509* x509;
15434
        int i;
15435
        if (opt != 0 && opt != 1) {
15436
            ret = WOLFSSL_FAILURE;
15437
            break;
15438
        }
15439
        /* Clear certificate chain */
15440
        FreeDer(&ctx->certChain);
15441
        if (sk) {
15442
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
15443
                x509 = wolfSSL_sk_X509_value(sk, i);
15444
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
15445
                if (wolfSSL_X509_up_ref(x509) != 1) {
15446
                    WOLFSSL_MSG("Error increasing reference count");
15447
                    continue;
15448
                }
15449
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
15450
                        WOLFSSL_SUCCESS) {
15451
                    WOLFSSL_MSG("Error adding certificate to context");
15452
                    /* Decrease reference count on failure */
15453
                    wolfSSL_X509_free(x509);
15454
                    x509 = NULL;
15455
                }
15456
            }
15457
        }
15458
        /* Free previous chain */
15459
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
15460
        ctx->x509Chain = sk;
15461
        if (sk && opt == 1) {
15462
            /* up all refs when opt == 1 */
15463
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
15464
                x509 = wolfSSL_sk_X509_value(sk, i);
15465
                if (wolfSSL_X509_up_ref(x509) != 1) {
15466
                    WOLFSSL_MSG("Error increasing reference count");
15467
                    continue;
15468
                }
15469
            }
15470
        }
15471
    }
15472
#else
15473
        WOLFSSL_MSG("Session certificates not compiled in");
15474
        ret = WOLFSSL_FAILURE;
15475
#endif
15476
        break;
15477
15478
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
15479
    case SSL_CTRL_OPTIONS:
15480
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
15481
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
15482
15483
        #ifdef WOLFSSL_QT
15484
        /* Set whether to use client or server cipher preference */
15485
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
15486
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
15487
            WOLFSSL_MSG("Using Server's Cipher Preference.");
15488
            ctx->useClientOrder = 0;
15489
        } else {
15490
            WOLFSSL_MSG("Using Client's Cipher Preference.");
15491
            ctx->useClientOrder = 1;
15492
        }
15493
        #endif /* WOLFSSL_QT */
15494
15495
        return ctrl_opt;
15496
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
15497
    case SSL_CTRL_EXTRA_CHAIN_CERT:
15498
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
15499
        if (pt == NULL) {
15500
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
15501
            ret = WOLFSSL_FAILURE;
15502
            break;
15503
        }
15504
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
15505
15506
#ifndef NO_DH
15507
    case SSL_CTRL_SET_TMP_DH:
15508
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
15509
        if (pt == NULL) {
15510
            WOLFSSL_MSG("Passed in DH pointer NULL.");
15511
            ret = WOLFSSL_FAILURE;
15512
            break;
15513
        }
15514
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
15515
#endif
15516
15517
#ifdef HAVE_ECC
15518
    case SSL_CTRL_SET_TMP_ECDH:
15519
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
15520
        if (pt == NULL) {
15521
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
15522
            ret = WOLFSSL_FAILURE;
15523
            break;
15524
        }
15525
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
15526
#endif
15527
    case SSL_CTRL_MODE:
15528
        wolfSSL_CTX_set_mode(ctx,opt);
15529
        break;
15530
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
15531
        WOLFSSL_MSG("set min proto version");
15532
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
15533
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
15534
        WOLFSSL_MSG("set max proto version");
15535
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
15536
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
15537
        WOLFSSL_MSG("get min proto version");
15538
        return wolfSSL_CTX_get_min_proto_version(ctx);
15539
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
15540
        WOLFSSL_MSG("get max proto version");
15541
        return wolfSSL_CTX_get_max_proto_version(ctx);
15542
    default:
15543
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
15544
        ret = WOLFSSL_FAILURE;
15545
        break;
15546
    }
15547
15548
    (void)ctx;
15549
    (void)cmd;
15550
    (void)opt;
15551
    (void)pt;
15552
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
15553
    return ret;
15554
}
15555
15556
#ifndef NO_WOLFSSL_STUB
15557
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
15558
{
15559
    (void) ctx;
15560
    (void) cmd;
15561
    (void) fp;
15562
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
15563
    return WOLFSSL_FAILURE;
15564
15565
}
15566
#endif /* NO_WOLFSSL_STUB */
15567
15568
#ifndef NO_WOLFSSL_STUB
15569
long wolfSSL_CTX_clear_extra_chain_certs(WOLFSSL_CTX* ctx)
15570
{
15571
    return wolfSSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0L, NULL);
15572
}
15573
#endif
15574
15575
/* Returns the verifyCallback from the ssl structure if successful.
15576
Returns NULL otherwise. */
15577
VerifyCallback wolfSSL_get_verify_callback(WOLFSSL* ssl)
15578
{
15579
    WOLFSSL_ENTER("wolfSSL_get_verify_callback");
15580
    if (ssl) {
15581
        return ssl->verifyCallback;
15582
    }
15583
    return NULL;
15584
}
15585
15586
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
15587
15588
15589
/* stunnel compatibility functions*/
15590
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
15591
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
15592
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
15593
     defined(WOLFSSL_OPENSSH)))
15594
void wolfSSL_ERR_remove_thread_state(void* pid)
15595
{
15596
    (void) pid;
15597
    return;
15598
}
15599
15600
#ifndef NO_FILESYSTEM
15601
/***TBD ***/
15602
void wolfSSL_print_all_errors_fp(XFILE fp)
15603
{
15604
    (void)fp;
15605
}
15606
#endif /* !NO_FILESYSTEM */
15607
15608
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
15609
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
15610
15611
/* Note: This is a huge section of API's - through
15612
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
15613
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
15614
15615
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
15616
    !defined(WOLFSSL_STATIC_MEMORY)
15617
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
15618
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
15619
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
15620
15621
static void* OSSL_Malloc(size_t size)
15622
{
15623
    if (ossl_malloc != NULL)
15624
        return ossl_malloc(size, NULL, 0);
15625
    else
15626
        return NULL;
15627
}
15628
15629
static void  OSSL_Free(void *ptr)
15630
{
15631
    if (ossl_free != NULL)
15632
        ossl_free(ptr, NULL, 0);
15633
}
15634
15635
static void* OSSL_Realloc(void *ptr, size_t size)
15636
{
15637
    if (ossl_realloc != NULL)
15638
        return ossl_realloc(ptr, size, NULL, 0);
15639
    else
15640
        return NULL;
15641
}
15642
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
15643
        * !WOLFSSL_STATIC_MEMORY */
15644
15645
int wolfSSL_CRYPTO_set_mem_functions(
15646
        wolfSSL_OSSL_Malloc_cb  m,
15647
        wolfSSL_OSSL_Realloc_cb r,
15648
        wolfSSL_OSSL_Free_cb    f)
15649
{
15650
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
15651
#ifdef WOLFSSL_DEBUG_MEMORY
15652
    WOLFSSL_MSG("mem functions will receive function name instead of "
15653
                "file name");
15654
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
15655
            (wolfSSL_Realloc_cb)r) == 0)
15656
        return WOLFSSL_SUCCESS;
15657
#else
15658
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
15659
                "functions will receive a NULL file name and 0 for the "
15660
                "line number.");
15661
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
15662
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
15663
        ossl_malloc = m;
15664
        ossl_free = f;
15665
        ossl_realloc = r;
15666
        return WOLFSSL_SUCCESS;
15667
    }
15668
#endif
15669
    else
15670
        return WOLFSSL_FAILURE;
15671
#else
15672
    (void)m;
15673
    (void)r;
15674
    (void)f;
15675
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
15676
    return WOLFSSL_FAILURE;
15677
#endif
15678
}
15679
15680
int wolfSSL_ERR_load_ERR_strings(void)
15681
{
15682
    return WOLFSSL_SUCCESS;
15683
}
15684
15685
void wolfSSL_ERR_load_crypto_strings(void)
15686
{
15687
    WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings");
15688
    /* Do nothing */
15689
    return;
15690
}
15691
15692
int wolfSSL_FIPS_mode(void)
15693
{
15694
#ifdef HAVE_FIPS
15695
    return 1;
15696
#else
15697
    return 0;
15698
#endif
15699
}
15700
15701
int wolfSSL_FIPS_mode_set(int r)
15702
{
15703
#ifdef HAVE_FIPS
15704
    if (r == 0) {
15705
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
15706
        return WOLFSSL_FAILURE;
15707
    }
15708
    return WOLFSSL_SUCCESS;
15709
#else
15710
    if (r == 0) {
15711
        return WOLFSSL_SUCCESS;
15712
    }
15713
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
15714
    return WOLFSSL_FAILURE;
15715
#endif
15716
}
15717
15718
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
15719
{
15720
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
15721
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
15722
15723
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
15724
    (void)alg_bits;
15725
    if (c!= NULL)
15726
        ret = c->bits;
15727
    #else
15728
    if (c != NULL && c->ssl != NULL) {
15729
        ret = 8 * c->ssl->specs.key_size;
15730
        if (alg_bits != NULL) {
15731
            *alg_bits = ret;
15732
        }
15733
    }
15734
    #endif
15735
    return ret;
15736
}
15737
15738
#ifdef HAVE_SNI
15739
int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name)
15740
{
15741
    int ret;
15742
    WOLFSSL_ENTER("wolfSSL_set_tlsext_host_name");
15743
    ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME,
15744
            host_name, (word16)XSTRLEN(host_name));
15745
    WOLFSSL_LEAVE("wolfSSL_set_tlsext_host_name", ret);
15746
    return ret;
15747
}
15748
15749
#ifndef NO_WOLFSSL_SERVER
15750
/* May be called by server to get the requested accepted name and by the client
15751
 * to get the requested name. */
15752
const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type)
15753
{
15754
    void * serverName = NULL;
15755
    if (ssl == NULL)
15756
        return NULL;
15757
    TLSX_SNI_GetRequest(ssl->extensions, type, &serverName,
15758
            !wolfSSL_is_server(ssl));
15759
    return (const char *)serverName;
15760
}
15761
#endif
15762
15763
#endif /* HAVE_SNI */
15764
15765
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
15766
{
15767
    int ret;
15768
    /* This method requires some explanation. Its sibling is
15769
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
15770
     * which re-inits the WOLFSSL* with all settings in the new CTX.
15771
     * That one is the right one to use *before* a handshake is started.
15772
     *
15773
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
15774
     * when a server inspects the SNI in a ClientHello callback and
15775
     * decides which set of certificates to use.
15776
     *
15777
     * Since, at the time the SNI callback is run, some decisions on
15778
     * Extensions or the ServerHello might already have been taken, this
15779
     * method is very restricted in what it does:
15780
     * - changing the server certificate(s)
15781
     * - changing the server id for session handling
15782
     * and everything else in WOLFSSL* needs to remain untouched.
15783
     */
15784
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
15785
    if (ssl == NULL || ctx == NULL)
15786
        return NULL;
15787
    if (ssl->ctx == ctx)
15788
        return ssl->ctx;
15789
15790
    if (ctx->suites == NULL) {
15791
        /* suites */
15792
        if (AllocateCtxSuites(ctx) != 0)
15793
            return NULL;
15794
        InitSSL_CTX_Suites(ctx);
15795
    }
15796
15797
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
15798
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
15799
    if (ret != 0) {
15800
        /* can only fail on serious stuff, like mutex not working
15801
         * or ctx refcount out of whack. */
15802
        return NULL;
15803
    }
15804
#else
15805
    (void)ret;
15806
#endif
15807
    if (ssl->ctx != NULL)
15808
        wolfSSL_CTX_free(ssl->ctx);
15809
    ssl->ctx = ctx;
15810
15811
#ifndef NO_CERTS
15812
#ifdef WOLFSSL_COPY_CERT
15813
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
15814
    if (ctx->certificate != NULL) {
15815
        if (ssl->buffers.certificate != NULL) {
15816
            FreeDer(&ssl->buffers.certificate);
15817
            ssl->buffers.certificate = NULL;
15818
        }
15819
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
15820
            ctx->certificate->length, ctx->certificate->type,
15821
            ctx->certificate->heap);
15822
        if (ret != 0) {
15823
            ssl->buffers.weOwnCert = 0;
15824
            return NULL;
15825
        }
15826
15827
        ssl->buffers.weOwnCert = 1;
15828
    }
15829
    if (ctx->certChain != NULL) {
15830
        if (ssl->buffers.certChain != NULL) {
15831
            FreeDer(&ssl->buffers.certChain);
15832
            ssl->buffers.certChain = NULL;
15833
        }
15834
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
15835
            ctx->certChain->length, ctx->certChain->type,
15836
            ctx->certChain->heap);
15837
        if (ret != 0) {
15838
            ssl->buffers.weOwnCertChain = 0;
15839
            return NULL;
15840
        }
15841
15842
        ssl->buffers.weOwnCertChain = 1;
15843
    }
15844
#else
15845
    /* ctx owns certificate, certChain and key */
15846
    ssl->buffers.certificate = ctx->certificate;
15847
    ssl->buffers.certChain = ctx->certChain;
15848
#endif
15849
#ifdef WOLFSSL_TLS13
15850
    ssl->buffers.certChainCnt = ctx->certChainCnt;
15851
#endif
15852
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
15853
#ifdef WOLFSSL_COPY_KEY
15854
    if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
15855
        FreeDer(&ssl->buffers.key);
15856
    }
15857
    if (ctx->privateKey != NULL) {
15858
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
15859
            ctx->privateKey->length, ctx->privateKey->type,
15860
            ctx->privateKey->heap);
15861
        if (ret != 0) {
15862
            ssl->buffers.weOwnKey = 0;
15863
            return NULL;
15864
        }
15865
        ssl->buffers.weOwnKey = 1;
15866
    }
15867
    else {
15868
        ssl->buffers.key      = ctx->privateKey;
15869
    }
15870
#else
15871
    ssl->buffers.key      = ctx->privateKey;
15872
#endif
15873
#else
15874
    if (ctx->privateKey != NULL) {
15875
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
15876
            ctx->privateKey->length, ctx->privateKey->type,
15877
            ctx->privateKey->heap);
15878
        if (ret != 0) {
15879
            return NULL;
15880
        }
15881
        /* Blind the private key for the SSL with new random mask. */
15882
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
15883
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
15884
            &ssl->buffers.keyMask);
15885
        if (ret != 0) {
15886
            return NULL;
15887
        }
15888
    }
15889
#endif
15890
    ssl->buffers.keyType  = ctx->privateKeyType;
15891
    ssl->buffers.keyId    = ctx->privateKeyId;
15892
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
15893
    ssl->buffers.keySz    = ctx->privateKeySz;
15894
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
15895
    /* flags indicating what certs/keys are available */
15896
    ssl->options.haveRSA          = ctx->haveRSA;
15897
    ssl->options.haveDH           = ctx->haveDH;
15898
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
15899
    ssl->options.haveECC          = ctx->haveECC;
15900
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
15901
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
15902
    ssl->options.haveDilithiumSig = ctx->haveDilithiumSig;
15903
#ifdef WOLFSSL_DUAL_ALG_CERTS
15904
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
15905
    ssl->buffers.altKey   = ctx->altPrivateKey;
15906
#else
15907
    if (ctx->altPrivateKey != NULL) {
15908
        ret = AllocCopyDer(&ssl->buffers.altKey, ctx->altPrivateKey->buffer,
15909
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
15910
            ctx->altPrivateKey->heap);
15911
        if (ret != 0) {
15912
            return NULL;
15913
        }
15914
        /* Blind the private key for the SSL with new random mask. */
15915
        wolfssl_priv_der_blind_toggle(ssl->buffers.altKey,
15916
                                      ctx->altPrivateKeyMask);
15917
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
15918
            &ssl->buffers.altKeyMask);
15919
        if (ret != 0) {
15920
            return NULL;
15921
        }
15922
    }
15923
#endif
15924
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
15925
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
15926
#endif /* WOLFSSL_DUAL_ALG_CERTS */
15927
#endif
15928
15929
#ifdef WOLFSSL_SESSION_ID_CTX
15930
    /* copy over application session context ID */
15931
    ssl->sessionCtxSz = ctx->sessionCtxSz;
15932
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
15933
#endif
15934
15935
    return ssl->ctx;
15936
}
15937
15938
15939
VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx)
15940
{
15941
    WOLFSSL_ENTER("wolfSSL_CTX_get_verify_callback");
15942
    if(ctx)
15943
        return ctx->verifyCallback;
15944
    return NULL;
15945
}
15946
15947
#ifdef HAVE_SNI
15948
/* this is a compatibility function, consider using
15949
 * wolfSSL_CTX_set_servername_callback */
15950
int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx,
15951
                                               CallbackSniRecv cb)
15952
{
15953
    WOLFSSL_ENTER("wolfSSL_CTX_set_tlsext_servername_callback");
15954
    if (ctx) {
15955
        ctx->sniRecvCb = cb;
15956
        return WOLFSSL_SUCCESS;
15957
    }
15958
    return WOLFSSL_FAILURE;
15959
}
15960
15961
#endif /* HAVE_SNI */
15962
15963
#ifndef NO_BIO
15964
void wolfSSL_ERR_load_BIO_strings(void) {
15965
    WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings");
15966
    /* do nothing */
15967
}
15968
#endif
15969
15970
#ifndef NO_WOLFSSL_STUB
15971
/* Set THREADID callback, return 1 on success, 0 on error */
15972
int wolfSSL_THREADID_set_callback(
15973
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
15974
{
15975
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
15976
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
15977
    (void)threadid_func;
15978
    return 1;
15979
}
15980
#endif
15981
15982
#ifndef NO_WOLFSSL_STUB
15983
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
15984
{
15985
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
15986
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
15987
    (void)id;
15988
    (void)val;
15989
    return;
15990
}
15991
#endif
15992
15993
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
15994
15995
#ifdef HAVE_SNI
15996
15997
void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb)
15998
0
{
15999
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_servername_callback");
16000
0
    if (ctx)
16001
0
        ctx->sniRecvCb = cb;
16002
0
}
16003
16004
16005
int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg)
16006
0
{
16007
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_servername_arg");
16008
0
    if (ctx) {
16009
0
        ctx->sniRecvCbArg = arg;
16010
0
        return WOLFSSL_SUCCESS;
16011
0
    }
16012
0
    return WOLFSSL_FAILURE;
16013
0
}
16014
16015
#endif /* HAVE_SNI */
16016
16017
#if defined(OPENSSL_EXTRA)
16018
16019
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
16020
{
16021
    if (!a || !b)
16022
        return -1;
16023
    return ConstantCompare((const byte*)a, (const byte*)b, (int)size);
16024
}
16025
16026
unsigned long wolfSSL_ERR_peek_last_error(void)
16027
{
16028
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
16029
16030
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
16031
    {
16032
        int ret;
16033
16034
        if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) {
16035
            WOLFSSL_MSG("Issue peeking at error node in queue");
16036
            return 0;
16037
        }
16038
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
16039
            return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
16040
    #if defined(WOLFSSL_PYTHON)
16041
        if (ret == ASN1_R_HEADER_TOO_LONG)
16042
            return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
16043
    #endif
16044
        return (unsigned long)ret;
16045
    }
16046
#else
16047
    return (unsigned long)(0 - NOT_COMPILED_IN);
16048
#endif
16049
}
16050
16051
#endif /* OPENSSL_EXTRA */
16052
16053
int wolfSSL_version(WOLFSSL* ssl)
16054
0
{
16055
0
    WOLFSSL_ENTER("wolfSSL_version");
16056
0
    if (ssl->version.major == SSLv3_MAJOR) {
16057
0
        switch (ssl->version.minor) {
16058
0
            case SSLv3_MINOR :
16059
0
                return SSL3_VERSION;
16060
0
            case TLSv1_MINOR :
16061
0
                return TLS1_VERSION;
16062
0
            case TLSv1_1_MINOR :
16063
0
                return TLS1_1_VERSION;
16064
0
            case TLSv1_2_MINOR :
16065
0
                return TLS1_2_VERSION;
16066
0
            case TLSv1_3_MINOR :
16067
0
                return TLS1_3_VERSION;
16068
0
            default:
16069
0
                return WOLFSSL_FAILURE;
16070
0
        }
16071
0
    }
16072
0
    else if (ssl->version.major == DTLS_MAJOR) {
16073
0
        switch (ssl->version.minor) {
16074
0
            case DTLS_MINOR :
16075
0
                return DTLS1_VERSION;
16076
0
            case DTLSv1_2_MINOR :
16077
0
                return DTLS1_2_VERSION;
16078
0
            case DTLSv1_3_MINOR:
16079
0
                return DTLS1_3_VERSION;
16080
0
            default:
16081
0
                return WOLFSSL_FAILURE;
16082
0
        }
16083
0
    }
16084
0
    return WOLFSSL_FAILURE;
16085
0
}
16086
16087
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
16088
0
{
16089
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
16090
0
    return ssl->ctx;
16091
0
}
16092
16093
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \
16094
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX)
16095
16096
/* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */
16097
int wolfSSL_get_verify_mode(const WOLFSSL* ssl)
16098
{
16099
    int mode = 0;
16100
    WOLFSSL_ENTER("wolfSSL_get_verify_mode");
16101
16102
    if (!ssl) {
16103
        return WOLFSSL_FAILURE;
16104
    }
16105
16106
    if (ssl->options.verifyNone) {
16107
        mode = WOLFSSL_VERIFY_NONE;
16108
    }
16109
    else {
16110
        if (ssl->options.verifyPeer) {
16111
            mode |= WOLFSSL_VERIFY_PEER;
16112
        }
16113
        if (ssl->options.failNoCert) {
16114
            mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
16115
        }
16116
        if (ssl->options.failNoCertxPSK) {
16117
            mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
16118
        }
16119
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16120
        if (ssl->options.verifyPostHandshake) {
16121
            mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
16122
        }
16123
#endif
16124
    }
16125
16126
    WOLFSSL_LEAVE("wolfSSL_get_verify_mode", mode);
16127
    return mode;
16128
}
16129
16130
int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx)
16131
{
16132
    int mode = 0;
16133
    WOLFSSL_ENTER("wolfSSL_CTX_get_verify_mode");
16134
16135
    if (!ctx) {
16136
        return WOLFSSL_FAILURE;
16137
    }
16138
16139
    if (ctx->verifyNone) {
16140
        mode = WOLFSSL_VERIFY_NONE;
16141
    }
16142
    else {
16143
        if (ctx->verifyPeer) {
16144
            mode |= WOLFSSL_VERIFY_PEER;
16145
        }
16146
        if (ctx->failNoCert) {
16147
            mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
16148
        }
16149
        if (ctx->failNoCertxPSK) {
16150
            mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
16151
        }
16152
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16153
        if (ctx->verifyPostHandshake) {
16154
            mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
16155
        }
16156
#endif
16157
    }
16158
16159
    WOLFSSL_LEAVE("wolfSSL_CTX_get_verify_mode", mode);
16160
    return mode;
16161
}
16162
16163
#endif
16164
16165
#ifdef WOLFSSL_JNI
16166
16167
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
16168
{
16169
    WOLFSSL_ENTER("wolfSSL_set_jobject");
16170
    if (ssl != NULL)
16171
    {
16172
        ssl->jObjectRef = objPtr;
16173
        return WOLFSSL_SUCCESS;
16174
    }
16175
    return WOLFSSL_FAILURE;
16176
}
16177
16178
void* wolfSSL_get_jobject(WOLFSSL* ssl)
16179
{
16180
    WOLFSSL_ENTER("wolfSSL_get_jobject");
16181
    if (ssl != NULL)
16182
        return ssl->jObjectRef;
16183
    return NULL;
16184
}
16185
16186
#endif /* WOLFSSL_JNI */
16187
16188
16189
#ifdef WOLFSSL_ASYNC_CRYPT
16190
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
16191
    WOLF_EVENT_FLAG flags, int* eventCount)
16192
{
16193
    if (ctx == NULL) {
16194
        return BAD_FUNC_ARG;
16195
    }
16196
16197
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
16198
                                        events, maxEvents, flags, eventCount);
16199
}
16200
16201
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
16202
{
16203
    int ret, eventCount = 0;
16204
    WOLF_EVENT* events[1];
16205
16206
    if (ssl == NULL) {
16207
        return BAD_FUNC_ARG;
16208
    }
16209
16210
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
16211
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
16212
    if (ret == 0) {
16213
        ret = eventCount;
16214
    }
16215
16216
    return ret;
16217
}
16218
#endif /* WOLFSSL_ASYNC_CRYPT */
16219
16220
#ifdef OPENSSL_EXTRA
16221
16222
static int peek_ignore_err(int err)
16223
{
16224
  switch(err) {
16225
    case -WC_NO_ERR_TRACE(WANT_READ):
16226
    case -WC_NO_ERR_TRACE(WANT_WRITE):
16227
    case -WC_NO_ERR_TRACE(ZERO_RETURN):
16228
    case -WOLFSSL_ERROR_ZERO_RETURN:
16229
    case -WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E):
16230
    case -WC_NO_ERR_TRACE(SOCKET_ERROR_E):
16231
      return 1;
16232
    default:
16233
      return 0;
16234
  }
16235
}
16236
16237
unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line,
16238
                                               const char **data, int *flags)
16239
{
16240
  unsigned long err;
16241
16242
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data");
16243
    err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err);
16244
16245
    if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
16246
        return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
16247
#ifdef OPENSSL_ALL
16248
    /* PARSE_ERROR is returned if an HTTP request is detected. */
16249
    else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR))
16250
        return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */;
16251
#endif
16252
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
16253
    else if (err == ASN1_R_HEADER_TOO_LONG)
16254
        return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
16255
#endif
16256
  return err;
16257
}
16258
#endif
16259
16260
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
16261
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
16262
16263
#if !defined(WOLFSSL_USER_IO)
16264
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
16265
 * example input would be "127.0.0.1" and the returned value would be 7F000001
16266
 */
16267
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
16268
{
16269
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
16270
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
16271
    int  af = WOLFSSL_IP4;
16272
    WOLFSSL_ASN1_STRING *ret = NULL;
16273
16274
    if (ipa == NULL)
16275
        return NULL;
16276
16277
    if (XSTRSTR(ipa, ":") != NULL) {
16278
        af = WOLFSSL_IP6;
16279
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
16280
    }
16281
16282
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
16283
#ifdef FREESCALE_MQX
16284
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
16285
#else
16286
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
16287
#endif
16288
        WOLFSSL_MSG("Error parsing IP address");
16289
        return NULL;
16290
    }
16291
16292
    ret = wolfSSL_ASN1_STRING_new();
16293
    if (ret != NULL) {
16294
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
16295
            WOLFSSL_MSG("Error setting the string");
16296
            wolfSSL_ASN1_STRING_free(ret);
16297
            ret = NULL;
16298
        }
16299
    }
16300
16301
    return ret;
16302
}
16303
#endif /* !WOLFSSL_USER_IO */
16304
16305
/* Is the specified cipher suite a fake one used an an extension proxy? */
16306
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
16307
{
16308
    (void)suite0;
16309
    (void)suite;
16310
#ifdef HAVE_RENEGOTIATION_INDICATION
16311
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
16312
        return 1;
16313
#endif
16314
    return 0;
16315
}
16316
16317
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
16318
        byte suite)
16319
{
16320
    const CipherSuiteInfo* cipher_names = GetCipherNames();
16321
    int cipherSz = GetCipherNamesSize();
16322
    int i;
16323
    for (i = 0; i < cipherSz; i++)
16324
        if (cipher_names[i].cipherSuite0 == suite0 &&
16325
                cipher_names[i].cipherSuite == suite)
16326
            break;
16327
    if (i == cipherSz)
16328
        return 1;
16329
    /* Check min version */
16330
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
16331
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
16332
                cipher_names[i].minor >= TLSv1_MINOR)
16333
            /* 1.0 ciphersuites are in general available in 1.1 and
16334
             * 1.1 ciphersuites are in general available in 1.2 */
16335
            return 0;
16336
        return 1;
16337
    }
16338
    /* Check max version */
16339
    switch (cipher_names[i].minor) {
16340
    case SSLv3_MINOR :
16341
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
16342
    case TLSv1_MINOR :
16343
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
16344
    case TLSv1_1_MINOR :
16345
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
16346
    case TLSv1_2_MINOR :
16347
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
16348
    case TLSv1_3_MINOR :
16349
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
16350
    default:
16351
        WOLFSSL_MSG("Unrecognized minor version");
16352
        return 1;
16353
    }
16354
}
16355
16356
/* returns a pointer to internal cipher suite list. Should not be free'd by
16357
 * caller.
16358
 */
16359
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
16360
{
16361
    const Suites* suites;
16362
#if defined(OPENSSL_ALL)
16363
    const CipherSuiteInfo* cipher_names = GetCipherNames();
16364
    int cipherSz = GetCipherNamesSize();
16365
#endif
16366
16367
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
16368
    if (ssl == NULL)
16369
        return NULL;
16370
16371
    suites = WOLFSSL_SUITES(ssl);
16372
    if (suites == NULL)
16373
        return NULL;
16374
16375
    /* check if stack needs populated */
16376
    if (ssl->suitesStack == NULL) {
16377
        int i;
16378
16379
        ((WOLFSSL*)ssl)->suitesStack =
16380
                wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, ssl->heap);
16381
        if (ssl->suitesStack == NULL)
16382
            return NULL;
16383
16384
        /* higher priority of cipher suite will be on top of stack */
16385
#if defined(OPENSSL_ALL)
16386
        for (i = suites->suiteSz - 2; i >=0; i-=2)
16387
#else
16388
        for (i = 0; i < suites->suiteSz; i+=2)
16389
#endif
16390
        {
16391
            struct WOLFSSL_CIPHER cipher;
16392
16393
            /* A couple of suites are placeholders for special options,
16394
             * skip those. */
16395
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
16396
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
16397
                                            suites->suites[i+1])) {
16398
                continue;
16399
            }
16400
16401
            XMEMSET(&cipher, 0, sizeof(cipher));
16402
            cipher.cipherSuite0 = suites->suites[i];
16403
            cipher.cipherSuite  = suites->suites[i+1];
16404
            cipher.ssl          = ssl;
16405
#if defined(OPENSSL_ALL)
16406
            cipher.in_stack     = 1;
16407
            {
16408
                int j;
16409
                for (j = 0; j < cipherSz; j++) {
16410
                    if (cipher_names[j].cipherSuite0 == cipher.cipherSuite0 &&
16411
                            cipher_names[j].cipherSuite == cipher.cipherSuite) {
16412
                        cipher.offset = (unsigned long)j;
16413
                        break;
16414
                    }
16415
                }
16416
            }
16417
#endif
16418
            if (wolfSSL_sk_insert(ssl->suitesStack, &cipher, 0) <= 0) {
16419
                WOLFSSL_MSG("Error inserting cipher onto stack");
16420
                wolfSSL_sk_CIPHER_free(ssl->suitesStack);
16421
                ((WOLFSSL*)ssl)->suitesStack = NULL;
16422
                break;
16423
            }
16424
        }
16425
16426
        /* If no ciphers were added, free empty stack and return NULL */
16427
        if (ssl->suitesStack != NULL && wolfSSL_sk_num(ssl->suitesStack) == 0) {
16428
            wolfSSL_sk_CIPHER_free(ssl->suitesStack);
16429
            ((WOLFSSL*)ssl)->suitesStack = NULL;
16430
        }
16431
    }
16432
    return ssl->suitesStack;
16433
}
16434
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
16435
#ifdef OPENSSL_ALL
16436
/* returned pointer is to an internal element in WOLFSSL struct and should not
16437
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
16438
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
16439
{
16440
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
16441
    const CipherSuiteInfo* cipher_names = GetCipherNames();
16442
    int cipherSz = GetCipherNamesSize();
16443
    const Suites* suites;
16444
16445
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
16446
16447
    if (ssl == NULL) {
16448
        return NULL;
16449
    }
16450
16451
    /* return NULL if is client side */
16452
    if (wolfSSL_is_server(ssl) == 0) {
16453
        return NULL;
16454
    }
16455
16456
    suites = ssl->clSuites;
16457
    if (suites == NULL) {
16458
        WOLFSSL_MSG("No client suites stored");
16459
    }
16460
    else if (ssl->clSuitesStack != NULL) {
16461
        ret = ssl->clSuitesStack;
16462
    }
16463
    else { /* generate cipher suites stack if not already done */
16464
        int i;
16465
        int j;
16466
16467
        ret = wolfSSL_sk_new_node(ssl->heap);
16468
        if (ret != NULL) {
16469
            ret->type = STACK_TYPE_CIPHER;
16470
16471
            /* higher priority of cipher suite will be on top of stack */
16472
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
16473
                WOLFSSL_CIPHER cipher;
16474
16475
                /* A couple of suites are placeholders for special options,
16476
                 * skip those. */
16477
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
16478
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
16479
                                                suites->suites[i+1])) {
16480
                    continue;
16481
                }
16482
16483
                cipher.cipherSuite0 = suites->suites[i];
16484
                cipher.cipherSuite  = suites->suites[i+1];
16485
                cipher.ssl          = ssl;
16486
                for (j = 0; j < cipherSz; j++) {
16487
                    if (cipher_names[j].cipherSuite0 ==
16488
                            cipher.cipherSuite0 &&
16489
                            cipher_names[j].cipherSuite ==
16490
                                    cipher.cipherSuite) {
16491
                        cipher.offset = (unsigned long)j;
16492
                        break;
16493
                    }
16494
                }
16495
16496
                /* in_stack is checked in wolfSSL_CIPHER_description */
16497
                cipher.in_stack     = 1;
16498
16499
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
16500
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
16501
                    wolfSSL_sk_CIPHER_free(ret);
16502
                    ret = NULL;
16503
                    break;
16504
                }
16505
            }
16506
        }
16507
        ssl->clSuitesStack = ret;
16508
    }
16509
    return ret;
16510
}
16511
#endif /* OPENSSL_ALL */
16512
16513
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
16514
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
16515
{
16516
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
16517
16518
    if (ctx == NULL)
16519
        return 0;
16520
16521
    return ctx->timeout;
16522
}
16523
16524
16525
/* returns the time in seconds of the current timeout */
16526
long wolfSSL_get_timeout(WOLFSSL* ssl)
16527
{
16528
    WOLFSSL_ENTER("wolfSSL_get_timeout");
16529
16530
    if (ssl == NULL)
16531
        return 0;
16532
    return ssl->timeout;
16533
}
16534
#endif
16535
16536
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
16537
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
16538
16539
#ifdef HAVE_ECC
16540
int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh)
16541
{
16542
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_set_tmp_ecdh");
16543
16544
    if (ctx == NULL || ecdh == NULL)
16545
        return BAD_FUNC_ARG;
16546
16547
    ctx->ecdhCurveOID = (word32)ecdh->group->curve_oid;
16548
16549
    return WOLFSSL_SUCCESS;
16550
}
16551
#endif
16552
#ifndef NO_BIO
16553
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
16554
{
16555
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
16556
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
16557
     * The setting buffer size doesn't do anything so return NULL for both.
16558
     */
16559
    if (s == NULL)
16560
        return NULL;
16561
16562
    return s->biord;
16563
}
16564
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
16565
{
16566
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
16567
    (void)s;
16568
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
16569
     * The setting buffer size doesn't do anything so return NULL for both.
16570
     */
16571
    if (s == NULL)
16572
        return NULL;
16573
16574
    return s->biowr;
16575
}
16576
#endif /* !NO_BIO */
16577
16578
#ifndef NO_TLS
16579
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
16580
{
16581
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
16582
    if (s == NULL)
16583
        return WOLFSSL_FAILURE;
16584
16585
    if (s->options.side == WOLFSSL_CLIENT_END) {
16586
    #ifndef NO_WOLFSSL_CLIENT
16587
        return wolfSSL_connect(s);
16588
    #else
16589
        WOLFSSL_MSG("Client not compiled in");
16590
        return WOLFSSL_FAILURE;
16591
    #endif
16592
    }
16593
16594
#ifndef NO_WOLFSSL_SERVER
16595
    return wolfSSL_accept(s);
16596
#else
16597
    WOLFSSL_MSG("Server not compiled in");
16598
    return WOLFSSL_FAILURE;
16599
#endif
16600
}
16601
16602
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
16603
{
16604
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
16605
#ifdef WOLFSSL_QUIC
16606
    if (WOLFSSL_IS_QUIC(s)) {
16607
        return wolfSSL_quic_do_handshake(s);
16608
    }
16609
#endif
16610
    return wolfSSL_SSL_do_handshake_internal(s);
16611
}
16612
#endif /* !NO_TLS */
16613
16614
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
16615
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
16616
#else
16617
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
16618
#endif
16619
{
16620
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
16621
16622
    return !wolfSSL_is_init_finished(ssl);
16623
}
16624
16625
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
16626
{
16627
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
16628
16629
    if (ssl == NULL)
16630
        return WOLFSSL_FAILURE;
16631
16632
    return ssl->options.handShakeState == NULL_STATE;
16633
}
16634
16635
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
16636
{
16637
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
16638
16639
    if (ssl == NULL)
16640
        return WOLFSSL_FAILURE;
16641
16642
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
16643
        return ssl->options.connectState > CONNECT_BEGIN &&
16644
            ssl->options.connectState < SECOND_REPLY_DONE;
16645
    }
16646
16647
    return ssl->options.acceptState > ACCEPT_BEGIN &&
16648
        ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
16649
}
16650
16651
#if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
16652
/* Expected return values from implementations of OpenSSL ticket key callback.
16653
 */
16654
#define TICKET_KEY_CB_RET_FAILURE    (-1)
16655
#define TICKET_KEY_CB_RET_NOT_FOUND   0
16656
#define TICKET_KEY_CB_RET_OK          1
16657
#define TICKET_KEY_CB_RET_RENEW       2
16658
16659
/* Implementation of session ticket encryption/decryption using OpenSSL
16660
 * callback to initialize the cipher and HMAC.
16661
 *
16662
 * ssl           The SSL/TLS object.
16663
 * keyName       The key name - used to identify the key to be used.
16664
 * iv            The IV to use.
16665
 * mac           The MAC of the encrypted data.
16666
 * enc           Encrypt ticket.
16667
 * encTicket     The ticket data.
16668
 * encTicketLen  The length of the ticket data.
16669
 * encLen        The encrypted/decrypted ticket length - output length.
16670
 * ctx           Ignored. Application specific data.
16671
 * returns WOLFSSL_TICKET_RET_OK to indicate success,
16672
 *         WOLFSSL_TICKET_RET_CREATE if a new ticket is required and
16673
 *         WOLFSSL_TICKET_RET_FATAL on error.
16674
 */
16675
static int wolfSSL_TicketKeyCb(WOLFSSL* ssl,
16676
        unsigned char keyName[WOLFSSL_TICKET_NAME_SZ],
16677
        unsigned char iv[WOLFSSL_TICKET_IV_SZ],
16678
        unsigned char mac[WOLFSSL_TICKET_MAC_SZ],
16679
        int enc, unsigned char* encTicket,
16680
        int encTicketLen, int* encLen, void* ctx)
16681
{
16682
    byte                    digest[WC_MAX_DIGEST_SIZE];
16683
    WC_DECLARE_VAR(evpCtx, WOLFSSL_EVP_CIPHER_CTX, 1, 0);
16684
    WOLFSSL_HMAC_CTX        hmacCtx;
16685
    unsigned int            mdSz = 0;
16686
    int                     len = 0;
16687
    int                     ret = WOLFSSL_TICKET_RET_FATAL;
16688
    int                     res;
16689
    int                     totalSz = 0;
16690
16691
    (void)ctx;
16692
16693
    WOLFSSL_ENTER("wolfSSL_TicketKeyCb");
16694
16695
    if (ssl == NULL || ssl->ctx == NULL || ssl->ctx->ticketEncWrapCb == NULL) {
16696
        WOLFSSL_MSG("Bad parameter");
16697
        return WOLFSSL_TICKET_RET_FATAL;
16698
    }
16699
16700
#ifdef WOLFSSL_SMALL_STACK
16701
    evpCtx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC(sizeof(*evpCtx), ssl->heap,
16702
                                               DYNAMIC_TYPE_TMP_BUFFER);
16703
    if (evpCtx == NULL) {
16704
        WOLFSSL_MSG("out of memory");
16705
        return WOLFSSL_TICKET_RET_FATAL;
16706
    }
16707
#endif
16708
16709
    /* Initialize the cipher and HMAC. */
16710
    wolfSSL_EVP_CIPHER_CTX_init(evpCtx);
16711
    if (wolfSSL_HMAC_CTX_Init(&hmacCtx) != WOLFSSL_SUCCESS) {
16712
        WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init error");
16713
        WC_FREE_VAR_EX(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
16714
        return WOLFSSL_TICKET_RET_FATAL;
16715
    }
16716
    res = ssl->ctx->ticketEncWrapCb(ssl, keyName,
16717
            iv, evpCtx, &hmacCtx, enc);
16718
    if (res != TICKET_KEY_CB_RET_OK && res != TICKET_KEY_CB_RET_RENEW) {
16719
        WOLFSSL_MSG("Ticket callback error");
16720
        ret = WOLFSSL_TICKET_RET_FATAL;
16721
        goto end;
16722
    }
16723
16724
    if (wolfSSL_HMAC_size(&hmacCtx) > WOLFSSL_TICKET_MAC_SZ) {
16725
        WOLFSSL_MSG("Ticket cipher MAC size error");
16726
        goto end;
16727
    }
16728
16729
    if (enc)
16730
    {
16731
        /* Encrypt in place. */
16732
        if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
16733
                                      encTicket, encTicketLen))
16734
            goto end;
16735
        totalSz = len;
16736
        if (totalSz > *encLen)
16737
            goto end;
16738
        if (!wolfSSL_EVP_EncryptFinal(evpCtx, &encTicket[len], &len))
16739
            goto end;
16740
        /* Total length of encrypted data. */
16741
        totalSz += len;
16742
        if (totalSz > *encLen)
16743
            goto end;
16744
16745
        /* HMAC the encrypted data into the parameter 'mac'. */
16746
        if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, totalSz))
16747
            goto end;
16748
        if (!wolfSSL_HMAC_Final(&hmacCtx, mac, &mdSz))
16749
            goto end;
16750
    }
16751
    else
16752
    {
16753
        /* HMAC the encrypted data and compare it to the passed in data. */
16754
        if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, encTicketLen))
16755
            goto end;
16756
        if (!wolfSSL_HMAC_Final(&hmacCtx, digest, &mdSz))
16757
            goto end;
16758
        if (ConstantCompare(mac, digest, (int)mdSz) != 0)
16759
            goto end;
16760
16761
        /* Decrypt the ticket data in place. */
16762
        if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
16763
                                      encTicket, encTicketLen))
16764
            goto end;
16765
        totalSz = len;
16766
        if (totalSz > encTicketLen)
16767
            goto end;
16768
        if (!wolfSSL_EVP_DecryptFinal(evpCtx, &encTicket[len], &len))
16769
            goto end;
16770
        /* Total length of decrypted data. */
16771
        totalSz += len;
16772
        if (totalSz > encTicketLen)
16773
            goto end;
16774
    }
16775
    *encLen = totalSz;
16776
16777
    if (res == TICKET_KEY_CB_RET_RENEW && !IsAtLeastTLSv1_3(ssl->version)
16778
            && !enc)
16779
        ret = WOLFSSL_TICKET_RET_CREATE;
16780
    else
16781
        ret = WOLFSSL_TICKET_RET_OK;
16782
end:
16783
16784
    (void)wc_HmacFree(&hmacCtx.hmac);
16785
    (void)wolfSSL_EVP_CIPHER_CTX_cleanup(evpCtx);
16786
16787
    WC_FREE_VAR_EX(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
16788
16789
    return ret;
16790
}
16791
16792
/* Set the callback to use when encrypting/decrypting tickets.
16793
 *
16794
 * ctx  The SSL/TLS context object.
16795
 * cb   The OpenSSL session ticket callback.
16796
 * returns WOLFSSL_SUCCESS to indicate success.
16797
 */
16798
int wolfSSL_CTX_set_tlsext_ticket_key_cb(WOLFSSL_CTX *ctx, ticketCompatCb cb)
16799
{
16800
16801
    /* Set the ticket encryption callback to be a wrapper around OpenSSL
16802
     * callback.
16803
     */
16804
    ctx->ticketEncCb = wolfSSL_TicketKeyCb;
16805
    ctx->ticketEncWrapCb = cb;
16806
16807
    return WOLFSSL_SUCCESS;
16808
}
16809
16810
#endif /* HAVE_SESSION_TICKET */
16811
16812
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
16813
    OPENSSL_EXTRA || HAVE_LIGHTY */
16814
16815
#if defined(HAVE_SESSION_TICKET) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \
16816
    !defined(NO_WOLFSSL_SERVER)
16817
/* Serialize the session ticket encryption keys.
16818
 *
16819
 * @param [in]  ctx     SSL/TLS context object.
16820
 * @param [in]  keys    Buffer to hold session ticket keys.
16821
 * @param [in]  keylen  Length of buffer.
16822
 * @return  WOLFSSL_SUCCESS on success.
16823
 * @return  WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
16824
 *          correct length.
16825
 */
16826
long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
16827
     unsigned char *keys, int keylen)
16828
{
16829
    if (ctx == NULL || keys == NULL) {
16830
        return WOLFSSL_FAILURE;
16831
    }
16832
    if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
16833
        return WOLFSSL_FAILURE;
16834
    }
16835
16836
    XMEMCPY(keys, ctx->ticketKeyCtx.name, WOLFSSL_TICKET_NAME_SZ);
16837
    keys += WOLFSSL_TICKET_NAME_SZ;
16838
    XMEMCPY(keys, ctx->ticketKeyCtx.key[0], WOLFSSL_TICKET_KEY_SZ);
16839
    keys += WOLFSSL_TICKET_KEY_SZ;
16840
    XMEMCPY(keys, ctx->ticketKeyCtx.key[1], WOLFSSL_TICKET_KEY_SZ);
16841
    keys += WOLFSSL_TICKET_KEY_SZ;
16842
    c32toa(ctx->ticketKeyCtx.expirary[0], keys);
16843
    keys += OPAQUE32_LEN;
16844
    c32toa(ctx->ticketKeyCtx.expirary[1], keys);
16845
16846
    return WOLFSSL_SUCCESS;
16847
}
16848
16849
/* Deserialize the session ticket encryption keys.
16850
 *
16851
 * @param [in]  ctx     SSL/TLS context object.
16852
 * @param [in]  keys    Session ticket keys.
16853
 * @param [in]  keylen  Length of data.
16854
 * @return  WOLFSSL_SUCCESS on success.
16855
 * @return  WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
16856
 *          correct length.
16857
 */
16858
long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
16859
     const void *keys_vp, int keylen)
16860
{
16861
    const byte* keys = (const byte*)keys_vp;
16862
    if (ctx == NULL || keys == NULL) {
16863
        return WOLFSSL_FAILURE;
16864
    }
16865
    if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
16866
        return WOLFSSL_FAILURE;
16867
    }
16868
16869
    XMEMCPY(ctx->ticketKeyCtx.name, keys, WOLFSSL_TICKET_NAME_SZ);
16870
    keys += WOLFSSL_TICKET_NAME_SZ;
16871
    XMEMCPY(ctx->ticketKeyCtx.key[0], keys, WOLFSSL_TICKET_KEY_SZ);
16872
    keys += WOLFSSL_TICKET_KEY_SZ;
16873
    XMEMCPY(ctx->ticketKeyCtx.key[1], keys, WOLFSSL_TICKET_KEY_SZ);
16874
    keys += WOLFSSL_TICKET_KEY_SZ;
16875
    ato32(keys, &ctx->ticketKeyCtx.expirary[0]);
16876
    keys += OPAQUE32_LEN;
16877
    ato32(keys, &ctx->ticketKeyCtx.expirary[1]);
16878
16879
    return WOLFSSL_SUCCESS;
16880
}
16881
#endif
16882
16883
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
16884
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
16885
int wolfSSL_CTX_get_extra_chain_certs(WOLFSSL_CTX* ctx,
16886
    WOLF_STACK_OF(X509)** chain)
16887
{
16888
    word32         idx;
16889
    word32         length;
16890
    WOLFSSL_STACK* node;
16891
    WOLFSSL_STACK* last = NULL;
16892
16893
    if (ctx == NULL || chain == NULL) {
16894
        chain = NULL;
16895
        return WOLFSSL_FAILURE;
16896
    }
16897
    if (ctx->x509Chain != NULL) {
16898
        *chain = ctx->x509Chain;
16899
        return WOLFSSL_SUCCESS;
16900
    }
16901
16902
    /* If there are no chains then success! */
16903
    *chain = NULL;
16904
    if (ctx->certChain == NULL || ctx->certChain->length == 0) {
16905
        return WOLFSSL_SUCCESS;
16906
    }
16907
16908
    /* Create a new stack of WOLFSSL_X509 object from chain buffer. */
16909
    for (idx = 0; idx < ctx->certChain->length; ) {
16910
        node = wolfSSL_sk_X509_new_null();
16911
        if (node == NULL)
16912
            return WOLFSSL_FAILURE;
16913
        node->next = NULL;
16914
16915
        /* 3 byte length | X509 DER data */
16916
        ato24(ctx->certChain->buffer + idx, &length);
16917
        idx += 3;
16918
16919
        /* Create a new X509 from DER encoded data. */
16920
        node->data.x509 = wolfSSL_X509_d2i_ex(NULL,
16921
            ctx->certChain->buffer + idx, (int)length, ctx->heap);
16922
        if (node->data.x509 == NULL) {
16923
            XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL);
16924
            /* Return as much of the chain as we created. */
16925
            ctx->x509Chain = *chain;
16926
            return WOLFSSL_FAILURE;
16927
        }
16928
        idx += length;
16929
16930
        /* Add object to the end of the stack. */
16931
        if (last == NULL) {
16932
            node->num = 1;
16933
            *chain = node;
16934
        }
16935
        else {
16936
            (*chain)->num++;
16937
            last->next = node;
16938
        }
16939
16940
        last = node;
16941
    }
16942
16943
    ctx->x509Chain = *chain;
16944
16945
    return WOLFSSL_SUCCESS;
16946
}
16947
16948
int wolfSSL_CTX_get0_chain_certs(WOLFSSL_CTX *ctx,
16949
        WOLF_STACK_OF(WOLFSSL_X509) **sk)
16950
{
16951
    WOLFSSL_ENTER("wolfSSL_CTX_get0_chain_certs");
16952
    if (ctx == NULL || sk == NULL) {
16953
        WOLFSSL_MSG("Bad parameter");
16954
        return WOLFSSL_FAILURE;
16955
    }
16956
16957
    /* This function should return ctx->x509Chain if it is populated, otherwise
16958
       it should be populated from ctx->certChain.  This matches the behavior of
16959
       wolfSSL_CTX_get_extra_chain_certs, so it is used directly. */
16960
    return wolfSSL_CTX_get_extra_chain_certs(ctx, sk);
16961
}
16962
16963
#ifdef KEEP_OUR_CERT
16964
int wolfSSL_get0_chain_certs(WOLFSSL *ssl,
16965
        WOLF_STACK_OF(WOLFSSL_X509) **sk)
16966
{
16967
    WOLFSSL_ENTER("wolfSSL_get0_chain_certs");
16968
    if (ssl == NULL || sk == NULL) {
16969
        WOLFSSL_MSG("Bad parameter");
16970
        return WOLFSSL_FAILURE;
16971
    }
16972
    *sk = ssl->ourCertChain;
16973
    return WOLFSSL_SUCCESS;
16974
}
16975
#endif
16976
16977
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
16978
{
16979
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
16980
16981
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
16982
}
16983
16984
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
16985
16986
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
16987
    defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \
16988
    defined(WOLFSSL_QUIC)
16989
#ifdef HAVE_ALPN
16990
void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data,
16991
                                unsigned int *len)
16992
{
16993
    word16 nameLen = 0;
16994
16995
    if (ssl != NULL && data != NULL && len != NULL) {
16996
        TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen);
16997
        *len = nameLen;
16998
    }
16999
}
17000
17001
int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen,
17002
                              const unsigned char *in, unsigned int inLen,
17003
                              const unsigned char *clientNames,
17004
                              unsigned int clientLen)
17005
{
17006
    unsigned int i, j;
17007
    byte lenIn, lenClient;
17008
17009
    if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL)
17010
        return WOLFSSL_NPN_UNSUPPORTED;
17011
17012
    for (i = 0; i < inLen; i += lenIn) {
17013
        lenIn = in[i++];
17014
        if (lenIn == 0 || i + lenIn > inLen)
17015
            break;
17016
        for (j = 0; j < clientLen; j += lenClient) {
17017
            lenClient = clientNames[j++];
17018
            if (lenClient == 0 || j + lenClient > clientLen)
17019
                break;
17020
17021
            if (lenIn != lenClient)
17022
                continue;
17023
17024
            if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) {
17025
                *out = (unsigned char *)(in + i);
17026
                *outLen = lenIn;
17027
                return WOLFSSL_NPN_NEGOTIATED;
17028
            }
17029
        }
17030
    }
17031
17032
    if (clientLen > 0 && (unsigned int)clientNames[0] + 1 <= clientLen) {
17033
        *out = (unsigned char *)clientNames + 1;
17034
        *outLen = clientNames[0];
17035
    }
17036
    else {
17037
        *out = (unsigned char *)clientNames;
17038
        *outLen = 0;
17039
    }
17040
    return WOLFSSL_NPN_NO_OVERLAP;
17041
}
17042
17043
void wolfSSL_set_alpn_select_cb(WOLFSSL *ssl,
17044
                                int (*cb) (WOLFSSL *ssl,
17045
                                           const unsigned char **out,
17046
                                           unsigned char *outlen,
17047
                                           const unsigned char *in,
17048
                                           unsigned int inlen,
17049
                                           void *arg), void *arg)
17050
{
17051
    if (ssl != NULL) {
17052
        ssl->alpnSelect = cb;
17053
        ssl->alpnSelectArg = arg;
17054
    }
17055
}
17056
17057
void wolfSSL_CTX_set_alpn_select_cb(WOLFSSL_CTX *ctx,
17058
                                    int (*cb) (WOLFSSL *ssl,
17059
                                               const unsigned char **out,
17060
                                               unsigned char *outlen,
17061
                                               const unsigned char *in,
17062
                                               unsigned int inlen,
17063
                                               void *arg), void *arg)
17064
{
17065
    if (ctx != NULL) {
17066
        ctx->alpnSelect = cb;
17067
        ctx->alpnSelectArg = arg;
17068
    }
17069
}
17070
17071
void wolfSSL_CTX_set_next_protos_advertised_cb(WOLFSSL_CTX *s,
17072
                                           int (*cb) (WOLFSSL *ssl,
17073
                                                      const unsigned char
17074
                                                      **out,
17075
                                                      unsigned int *outlen,
17076
                                                      void *arg), void *arg)
17077
{
17078
    (void)s;
17079
    (void)cb;
17080
    (void)arg;
17081
    WOLFSSL_STUB("wolfSSL_CTX_set_next_protos_advertised_cb");
17082
}
17083
17084
void wolfSSL_CTX_set_next_proto_select_cb(WOLFSSL_CTX *s,
17085
                                      int (*cb) (WOLFSSL *ssl,
17086
                                                 unsigned char **out,
17087
                                                 unsigned char *outlen,
17088
                                                 const unsigned char *in,
17089
                                                 unsigned int inlen,
17090
                                                 void *arg), void *arg)
17091
{
17092
    (void)s;
17093
    (void)cb;
17094
    (void)arg;
17095
    WOLFSSL_STUB("wolfSSL_CTX_set_next_proto_select_cb");
17096
}
17097
17098
void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s,
17099
    const unsigned char **data, unsigned *len)
17100
{
17101
    (void)s;
17102
    (void)data;
17103
    (void)len;
17104
    WOLFSSL_STUB("wolfSSL_get0_next_proto_negotiated");
17105
}
17106
#endif /* HAVE_ALPN */
17107
17108
#endif /* WOLFSSL_NGINX  / WOLFSSL_HAPROXY */
17109
17110
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
17111
int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id)
17112
{
17113
    int ret = 0;
17114
17115
    WOLFSSL_ENTER("wolfSSL_curve_is_disabled");
17116
    WOLFSSL_MSG_EX("wolfSSL_curve_is_disabled checking for %d", curve_id);
17117
17118
    /* (curve_id >= WOLFSSL_FFDHE_START) - DH parameters are never disabled. */
17119
    if (curve_id < WOLFSSL_FFDHE_START) {
17120
        if (curve_id > WOLFSSL_ECC_MAX_AVAIL) {
17121
            WOLFSSL_MSG("Curve id out of supported range");
17122
            /* Disabled if not in valid range. */
17123
            ret = 1;
17124
        }
17125
        else if (curve_id >= 32) {
17126
            /* 0 is for invalid and 1-14 aren't used otherwise. */
17127
            ret = (ssl->disabledCurves & (1U << (curve_id - 32))) != 0;
17128
        }
17129
        else {
17130
            ret = (ssl->disabledCurves & (1U << curve_id)) != 0;
17131
        }
17132
    }
17133
17134
    WOLFSSL_LEAVE("wolfSSL_curve_is_disabled", ret);
17135
    return ret;
17136
}
17137
17138
#if (defined(HAVE_ECC) || \
17139
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
17140
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
17141
17142
const WOLF_EC_NIST_NAME kNistCurves[] = {
17143
#ifdef HAVE_ECC
17144
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
17145
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
17146
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
17147
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
17148
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
17149
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
17150
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
17151
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
17152
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
17153
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
17154
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
17155
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
17156
     WOLFSSL_ECC_BRAINPOOLP256R1},
17157
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
17158
     WOLFSSL_ECC_BRAINPOOLP384R1},
17159
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
17160
     WOLFSSL_ECC_BRAINPOOLP512R1},
17161
#endif
17162
#ifdef HAVE_CURVE25519
17163
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
17164
#endif
17165
#ifdef HAVE_CURVE448
17166
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
17167
#endif
17168
#ifdef WOLFSSL_HAVE_MLKEM
17169
#ifndef WOLFSSL_NO_ML_KEM
17170
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
17171
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
17172
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
17173
#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC)
17174
    #ifdef WOLFSSL_PQC_HYBRIDS
17175
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
17176
     WOLFSSL_SECP256R1MLKEM768},
17177
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
17178
     WOLFSSL_SECP384R1MLKEM1024},
17179
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
17180
     WOLFSSL_X25519MLKEM768},
17181
    #endif /* WOLFSSL_PQC_HYBRIDS */
17182
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
17183
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
17184
     WOLFSSL_SECP256R1MLKEM512},
17185
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
17186
     WOLFSSL_SECP384R1MLKEM768},
17187
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
17188
     WOLFSSL_SECP521R1MLKEM1024},
17189
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
17190
     WOLFSSL_X25519MLKEM512},
17191
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
17192
     WOLFSSL_X448MLKEM768},
17193
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
17194
#endif
17195
#endif /* !WOLFSSL_NO_ML_KEM */
17196
#ifdef WOLFSSL_MLKEM_KYBER
17197
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
17198
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
17199
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
17200
#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC)
17201
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
17202
     WOLFSSL_P256_KYBER_LEVEL1},
17203
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
17204
     WOLFSSL_P384_KYBER_LEVEL3},
17205
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
17206
     WOLFSSL_P256_KYBER_LEVEL3},
17207
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
17208
     WOLFSSL_P521_KYBER_LEVEL5},
17209
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
17210
     WOLFSSL_X25519_KYBER_LEVEL1},
17211
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
17212
     WOLFSSL_X448_KYBER_LEVEL3},
17213
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
17214
     WOLFSSL_X25519_KYBER_LEVEL3},
17215
#endif
17216
#endif /* WOLFSSL_MLKEM_KYBER */
17217
#endif /* WOLFSSL_HAVE_MLKEM */
17218
#ifdef WOLFSSL_SM2
17219
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
17220
#endif
17221
#ifdef HAVE_ECC
17222
    /* Alternative curve names */
17223
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
17224
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
17225
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
17226
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
17227
#endif
17228
#ifdef WOLFSSL_SM2
17229
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
17230
#endif
17231
    {0, NULL, 0, 0},
17232
};
17233
17234
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
17235
        byte curves_only)
17236
{
17237
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
17238
    word16 curve;
17239
    word32 disabled;
17240
    char name[MAX_CURVE_NAME_SZ];
17241
    byte groups_len = 0;
17242
#ifdef WOLFSSL_SMALL_STACK
17243
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
17244
    int *groups;
17245
#else
17246
    int groups[WOLFSSL_MAX_GROUP_COUNT];
17247
#endif
17248
    const WOLF_EC_NIST_NAME* nist_name;
17249
17250
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
17251
        DYNAMIC_TYPE_TMP_BUFFER,
17252
    {
17253
        ret=MEMORY_E;
17254
        goto leave;
17255
    });
17256
17257
    for (idx = 1; names[idx-1] != '\0'; idx++) {
17258
        if (names[idx] != ':' && names[idx] != '\0')
17259
            continue;
17260
17261
        len = idx - start;
17262
        if (len > MAX_CURVE_NAME_SZ - 1)
17263
            goto leave;
17264
17265
        XMEMCPY(name, names + start, (size_t)len);
17266
        name[len] = 0;
17267
        curve = WOLFSSL_NAMED_GROUP_INVALID;
17268
17269
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
17270
            if (len == nist_name->name_len &&
17271
                    XSTRNCMP(name, nist_name->name, (size_t)len) == 0) {
17272
                curve = nist_name->curve;
17273
                break;
17274
            }
17275
        }
17276
17277
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
17278
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
17279
            int   nret;
17280
            const ecc_set_type *eccSet;
17281
17282
            nret = wc_ecc_get_curve_idx_from_name(name);
17283
            if (nret < 0) {
17284
                WOLFSSL_MSG("Could not find name in set");
17285
                goto leave;
17286
            }
17287
17288
            eccSet = wc_ecc_get_curve_params(nret);
17289
            if (eccSet == NULL) {
17290
                WOLFSSL_MSG("NULL set returned");
17291
                goto leave;
17292
            }
17293
17294
            curve = GetCurveByOID((int)eccSet->oidSum);
17295
        #else
17296
            WOLFSSL_MSG("API not present to search farther using name");
17297
            goto leave;
17298
        #endif
17299
        }
17300
17301
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
17302
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
17303
            WOLFSSL_MSG("curve value is not supported");
17304
            goto leave;
17305
        }
17306
17307
        for (i = 0; i < groups_len; ++i) {
17308
            if (groups[i] == curve) {
17309
                /* silently drop duplicates */
17310
                break;
17311
            }
17312
        }
17313
        if (i >= groups_len) {
17314
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
17315
                WOLFSSL_MSG_EX("setting %d or more supported "
17316
                               "curves is not permitted", groups_len);
17317
                goto leave;
17318
            }
17319
            groups[groups_len++] = (int)curve;
17320
        }
17321
17322
        start = idx + 1;
17323
    }
17324
17325
    /* Disable all curves so that only the ones the user wants are enabled. */
17326
    disabled = 0xFFFFFFFFUL;
17327
    for (i = 0; i < groups_len; ++i) {
17328
        /* Switch the bit to off and therefore is enabled. */
17329
        curve = (word16)groups[i];
17330
        if (curve >= 64) {
17331
            WC_DO_NOTHING;
17332
        }
17333
        else if (curve >= 32) {
17334
            /* 0 is for invalid and 1-14 aren't used otherwise. */
17335
            disabled &= ~(1U << (curve - 32));
17336
        }
17337
        else {
17338
            disabled &= ~(1U << curve);
17339
        }
17340
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
17341
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
17342
        /* using the wolfSSL API to set the groups, this will populate
17343
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
17344
         * The order in (ssl|ctx)->groups will then be respected
17345
         * when TLSX_KEY_SHARE needs to be established */
17346
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
17347
                        != WOLFSSL_SUCCESS)
17348
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
17349
                           != WOLFSSL_SUCCESS)) {
17350
            WOLFSSL_MSG("Unable to set supported curve");
17351
            goto leave;
17352
        }
17353
    #elif !defined(NO_WOLFSSL_CLIENT)
17354
        /* set the supported curve so client TLS extension contains only the
17355
         * desired curves */
17356
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
17357
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
17358
                           != WOLFSSL_SUCCESS)) {
17359
            WOLFSSL_MSG("Unable to set supported curve");
17360
            goto leave;
17361
        }
17362
    #endif
17363
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
17364
    }
17365
17366
    if (ssl != NULL)
17367
        ssl->disabledCurves = disabled;
17368
    else if (ctx != NULL)
17369
        ctx->disabledCurves = disabled;
17370
    ret = WOLFSSL_SUCCESS;
17371
17372
leave:
17373
#ifdef WOLFSSL_SMALL_STACK
17374
    if (groups)
17375
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
17376
#endif
17377
    return ret;
17378
}
17379
17380
int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names)
17381
{
17382
    WOLFSSL_ENTER("wolfSSL_CTX_set1_curves_list");
17383
    if (ctx == NULL || names == NULL) {
17384
        WOLFSSL_MSG("ctx or names was NULL");
17385
        return WOLFSSL_FAILURE;
17386
    }
17387
    return set_curves_list(NULL, ctx, names, 1);
17388
}
17389
17390
int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names)
17391
{
17392
    WOLFSSL_ENTER("wolfSSL_set1_curves_list");
17393
    if (ssl == NULL || names == NULL) {
17394
        WOLFSSL_MSG("ssl or names was NULL");
17395
        return WOLFSSL_FAILURE;
17396
    }
17397
    return set_curves_list(ssl, NULL, names, 1);
17398
}
17399
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
17400
#endif /* OPENSSL_EXTRA || HAVE_CURL */
17401
17402
17403
#ifdef OPENSSL_EXTRA
17404
/* Sets a callback for when sending and receiving protocol messages.
17405
 * This callback is copied to all WOLFSSL objects created from the ctx.
17406
 *
17407
 * ctx WOLFSSL_CTX structure to set callback in
17408
 * cb  callback to use
17409
 *
17410
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
17411
 */
17412
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
17413
{
17414
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
17415
    if (ctx == NULL) {
17416
        WOLFSSL_MSG("Null ctx passed in");
17417
        return WOLFSSL_FAILURE;
17418
    }
17419
17420
    ctx->protoMsgCb = cb;
17421
    return WOLFSSL_SUCCESS;
17422
}
17423
17424
17425
/* Sets a callback for when sending and receiving protocol messages.
17426
 *
17427
 * ssl WOLFSSL structure to set callback in
17428
 * cb  callback to use
17429
 *
17430
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
17431
 */
17432
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
17433
{
17434
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
17435
17436
    if (ssl == NULL) {
17437
        return WOLFSSL_FAILURE;
17438
    }
17439
17440
    if (cb != NULL) {
17441
        ssl->toInfoOn = 1;
17442
    }
17443
17444
    ssl->protoMsgCb = cb;
17445
    return WOLFSSL_SUCCESS;
17446
}
17447
17448
17449
/* set the user argument to pass to the msg callback when called
17450
 * return WOLFSSL_SUCCESS on success */
17451
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
17452
{
17453
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
17454
    if (ctx == NULL) {
17455
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
17456
        return WOLFSSL_FAILURE;
17457
    }
17458
17459
    ctx->protoMsgCtx = arg;
17460
    return WOLFSSL_SUCCESS;
17461
}
17462
17463
17464
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
17465
{
17466
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
17467
    if (ssl == NULL)
17468
        return WOLFSSL_FAILURE;
17469
17470
    ssl->protoMsgCtx = arg;
17471
    return WOLFSSL_SUCCESS;
17472
}
17473
17474
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
17475
    int line)
17476
{
17477
    void *ret;
17478
    (void)file;
17479
    (void)line;
17480
17481
    if (data == NULL || siz >= INT_MAX)
17482
        return NULL;
17483
17484
    ret = wolfSSL_OPENSSL_malloc(siz);
17485
    if (ret == NULL) {
17486
        return NULL;
17487
    }
17488
    return XMEMCPY(ret, data, siz);
17489
}
17490
17491
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
17492
{
17493
    if (ptr)
17494
        ForceZero(ptr, (word32)len);
17495
}
17496
17497
int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p,
17498
                            unsigned int p_len)
17499
{
17500
    WOLFSSL_ENTER("wolfSSL_CTX_set_alpn_protos");
17501
    if (ctx == NULL)
17502
        return BAD_FUNC_ARG;
17503
    if (ctx->alpn_cli_protos != NULL) {
17504
        XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL);
17505
    }
17506
17507
    ctx->alpn_cli_protos = (const unsigned char*)XMALLOC(p_len,
17508
        ctx->heap, DYNAMIC_TYPE_OPENSSL);
17509
    if (ctx->alpn_cli_protos == NULL) {
17510
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17511
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17512
         * the function reverses the return value convention.
17513
         */
17514
        return 1;
17515
#else
17516
        return WOLFSSL_FAILURE;
17517
#endif
17518
    }
17519
    XMEMCPY((void*)ctx->alpn_cli_protos, p, p_len);
17520
    ctx->alpn_cli_protos_len = p_len;
17521
17522
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17523
    /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17524
     * the function reverses the return value convention.
17525
     */
17526
    return 0;
17527
#else
17528
    return WOLFSSL_SUCCESS;
17529
#endif
17530
}
17531
17532
17533
#ifdef HAVE_ALPN
17534
#ifndef NO_BIO
17535
/* Sets the ALPN extension protos
17536
 *
17537
 * example format is
17538
 * unsigned char p[] = {
17539
 *      8, 'h', 't', 't', 'p', '/', '1', '.', '1'
17540
 * };
17541
 *
17542
 * returns WOLFSSL_SUCCESS on success */
17543
int wolfSSL_set_alpn_protos(WOLFSSL* ssl,
17544
        const unsigned char* p, unsigned int p_len)
17545
{
17546
    char* pt = NULL;
17547
    unsigned int ptIdx;
17548
    unsigned int sz;
17549
    unsigned int idx = 0;
17550
    int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH;
17551
    int ret;
17552
17553
    WOLFSSL_ENTER("wolfSSL_set_alpn_protos");
17554
17555
    if (ssl == NULL || p_len <= 1) {
17556
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17557
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17558
         * the function reverses the return value convention.
17559
         */
17560
        return 1;
17561
#else
17562
        return WOLFSSL_FAILURE;
17563
#endif
17564
    }
17565
17566
    /* Replacing leading number with trailing ',' and adding '\0'. */
17567
    pt = (char*)XMALLOC(p_len + 1, ssl->heap, DYNAMIC_TYPE_OPENSSL);
17568
    if (pt == NULL) {
17569
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17570
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17571
         * the function reverses the return value convention.
17572
         */
17573
        return 1;
17574
#else
17575
        return WOLFSSL_FAILURE;
17576
#endif
17577
    }
17578
17579
    ptIdx = 0;
17580
    /* convert into comma separated list */
17581
    while (idx < p_len - 1) {
17582
        unsigned int i;
17583
17584
        sz = p[idx++];
17585
        if (idx + sz > p_len) {
17586
            WOLFSSL_MSG("Bad list format");
17587
            XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL);
17588
    #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17589
            /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17590
             * the function reverses the return value convention.
17591
             */
17592
            return 1;
17593
    #else
17594
            return WOLFSSL_FAILURE;
17595
    #endif
17596
        }
17597
        if (sz > 0) {
17598
            for (i = 0; i < sz; i++) {
17599
                pt[ptIdx++] = p[idx++];
17600
            }
17601
            if (idx < p_len - 1) {
17602
                pt[ptIdx++] = ',';
17603
            }
17604
        }
17605
    }
17606
    pt[ptIdx++] = '\0';
17607
17608
    /* clears out all current ALPN extensions set */
17609
    TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap);
17610
17611
    ret = wolfSSL_UseALPN(ssl, pt, ptIdx, (byte)alpn_opt);
17612
    XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL);
17613
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
17614
    /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
17615
     * the function reverses the return value convention.
17616
     */
17617
    if (ret != WOLFSSL_SUCCESS)
17618
        return 1;
17619
    return 0;
17620
#else
17621
    if (ret != WOLFSSL_SUCCESS)
17622
        return WOLFSSL_FAILURE;
17623
    return WOLFSSL_SUCCESS;
17624
#endif
17625
}
17626
#endif /* !NO_BIO */
17627
#endif /* HAVE_ALPN */
17628
#endif /* OPENSSL_EXTRA */
17629
17630
#if defined(OPENSSL_EXTRA)
17631
17632
#ifndef NO_BIO
17633
#define WOLFSSL_BIO_INCLUDED
17634
#include "src/bio.c"
17635
#endif
17636
17637
#endif /* OPENSSL_EXTRA */
17638
17639
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
17640
17641
word32 nid2oid(int nid, int grp)
17642
{
17643
    /* get OID type */
17644
    switch (grp) {
17645
        /* oidHashType */
17646
        case oidHashType:
17647
            switch (nid) {
17648
            #ifdef WOLFSSL_MD2
17649
                case WC_NID_md2:
17650
                    return MD2h;
17651
            #endif
17652
            #ifndef NO_MD5
17653
                case WC_NID_md5:
17654
                    return MD5h;
17655
            #endif
17656
            #ifndef NO_SHA
17657
                case WC_NID_sha1:
17658
                    return SHAh;
17659
            #endif
17660
                case WC_NID_sha224:
17661
                    return SHA224h;
17662
            #ifndef NO_SHA256
17663
                case WC_NID_sha256:
17664
                    return SHA256h;
17665
            #endif
17666
            #ifdef WOLFSSL_SHA384
17667
                case WC_NID_sha384:
17668
                    return SHA384h;
17669
            #endif
17670
            #ifdef WOLFSSL_SHA512
17671
                case WC_NID_sha512:
17672
                    return SHA512h;
17673
            #endif
17674
            #ifndef WOLFSSL_NOSHA3_224
17675
                case WC_NID_sha3_224:
17676
                    return SHA3_224h;
17677
            #endif
17678
            #ifndef WOLFSSL_NOSHA3_256
17679
                case WC_NID_sha3_256:
17680
                    return SHA3_256h;
17681
            #endif
17682
            #ifndef WOLFSSL_NOSHA3_384
17683
                case WC_NID_sha3_384:
17684
                    return SHA3_384h;
17685
            #endif
17686
            #ifndef WOLFSSL_NOSHA3_512
17687
                case WC_NID_sha3_512:
17688
                    return SHA3_512h;
17689
            #endif
17690
            }
17691
            break;
17692
17693
        /*  oidSigType */
17694
        case oidSigType:
17695
            switch (nid) {
17696
            #ifndef NO_DSA
17697
                case WC_NID_dsaWithSHA1:
17698
                    return CTC_SHAwDSA;
17699
                case WC_NID_dsa_with_SHA256:
17700
                    return CTC_SHA256wDSA;
17701
            #endif /* NO_DSA */
17702
            #ifndef NO_RSA
17703
                case WC_NID_md2WithRSAEncryption:
17704
                    return CTC_MD2wRSA;
17705
                case WC_NID_md5WithRSAEncryption:
17706
                    return CTC_MD5wRSA;
17707
                case WC_NID_sha1WithRSAEncryption:
17708
                    return CTC_SHAwRSA;
17709
                case WC_NID_sha224WithRSAEncryption:
17710
                    return CTC_SHA224wRSA;
17711
                case WC_NID_sha256WithRSAEncryption:
17712
                    return CTC_SHA256wRSA;
17713
                case WC_NID_sha384WithRSAEncryption:
17714
                    return CTC_SHA384wRSA;
17715
                case WC_NID_sha512WithRSAEncryption:
17716
                    return CTC_SHA512wRSA;
17717
                #ifdef WOLFSSL_SHA3
17718
                case WC_NID_RSA_SHA3_224:
17719
                    return CTC_SHA3_224wRSA;
17720
                case WC_NID_RSA_SHA3_256:
17721
                    return CTC_SHA3_256wRSA;
17722
                case WC_NID_RSA_SHA3_384:
17723
                    return CTC_SHA3_384wRSA;
17724
                case WC_NID_RSA_SHA3_512:
17725
                    return CTC_SHA3_512wRSA;
17726
                #endif
17727
            #endif /* NO_RSA */
17728
            #ifdef HAVE_ECC
17729
                case WC_NID_ecdsa_with_SHA1:
17730
                    return CTC_SHAwECDSA;
17731
                case WC_NID_ecdsa_with_SHA224:
17732
                    return CTC_SHA224wECDSA;
17733
                case WC_NID_ecdsa_with_SHA256:
17734
                    return CTC_SHA256wECDSA;
17735
                case WC_NID_ecdsa_with_SHA384:
17736
                    return CTC_SHA384wECDSA;
17737
                case WC_NID_ecdsa_with_SHA512:
17738
                    return CTC_SHA512wECDSA;
17739
                #ifdef WOLFSSL_SHA3
17740
                case WC_NID_ecdsa_with_SHA3_224:
17741
                    return CTC_SHA3_224wECDSA;
17742
                case WC_NID_ecdsa_with_SHA3_256:
17743
                    return CTC_SHA3_256wECDSA;
17744
                case WC_NID_ecdsa_with_SHA3_384:
17745
                    return CTC_SHA3_384wECDSA;
17746
                case WC_NID_ecdsa_with_SHA3_512:
17747
                    return CTC_SHA3_512wECDSA;
17748
                #endif
17749
            #endif /* HAVE_ECC */
17750
            }
17751
            break;
17752
17753
        /* oidKeyType */
17754
        case oidKeyType:
17755
            switch (nid) {
17756
            #ifndef NO_DSA
17757
                case WC_NID_dsa:
17758
                    return DSAk;
17759
            #endif /* NO_DSA */
17760
            #ifndef NO_RSA
17761
                case WC_NID_rsaEncryption:
17762
                    return RSAk;
17763
            #endif /* NO_RSA */
17764
            #ifdef HAVE_ECC
17765
                case WC_NID_X9_62_id_ecPublicKey:
17766
                    return ECDSAk;
17767
            #endif /* HAVE_ECC */
17768
            }
17769
            break;
17770
17771
17772
    #ifdef HAVE_ECC
17773
        case oidCurveType:
17774
            switch (nid) {
17775
            case WC_NID_X9_62_prime192v1:
17776
                return ECC_SECP192R1_OID;
17777
            case WC_NID_X9_62_prime192v2:
17778
                return ECC_PRIME192V2_OID;
17779
            case WC_NID_X9_62_prime192v3:
17780
                return ECC_PRIME192V3_OID;
17781
            case WC_NID_X9_62_prime239v1:
17782
                return ECC_PRIME239V1_OID;
17783
            case WC_NID_X9_62_prime239v2:
17784
                return ECC_PRIME239V2_OID;
17785
            case WC_NID_X9_62_prime239v3:
17786
                return ECC_PRIME239V3_OID;
17787
            case WC_NID_X9_62_prime256v1:
17788
                return ECC_SECP256R1_OID;
17789
            case WC_NID_secp112r1:
17790
                return ECC_SECP112R1_OID;
17791
            case WC_NID_secp112r2:
17792
                return ECC_SECP112R2_OID;
17793
            case WC_NID_secp128r1:
17794
                return ECC_SECP128R1_OID;
17795
            case WC_NID_secp128r2:
17796
                return ECC_SECP128R2_OID;
17797
            case WC_NID_secp160r1:
17798
                return ECC_SECP160R1_OID;
17799
            case WC_NID_secp160r2:
17800
                return ECC_SECP160R2_OID;
17801
            case WC_NID_secp224r1:
17802
                return ECC_SECP224R1_OID;
17803
            case WC_NID_secp384r1:
17804
                return ECC_SECP384R1_OID;
17805
            case WC_NID_secp521r1:
17806
                return ECC_SECP521R1_OID;
17807
            case WC_NID_secp160k1:
17808
                return ECC_SECP160K1_OID;
17809
            case WC_NID_secp192k1:
17810
                return ECC_SECP192K1_OID;
17811
            case WC_NID_secp224k1:
17812
                return ECC_SECP224K1_OID;
17813
            case WC_NID_secp256k1:
17814
                return ECC_SECP256K1_OID;
17815
            case WC_NID_brainpoolP160r1:
17816
                return ECC_BRAINPOOLP160R1_OID;
17817
            case WC_NID_brainpoolP192r1:
17818
                return ECC_BRAINPOOLP192R1_OID;
17819
            case WC_NID_brainpoolP224r1:
17820
                return ECC_BRAINPOOLP224R1_OID;
17821
            case WC_NID_brainpoolP256r1:
17822
                return ECC_BRAINPOOLP256R1_OID;
17823
            case WC_NID_brainpoolP320r1:
17824
                return ECC_BRAINPOOLP320R1_OID;
17825
            case WC_NID_brainpoolP384r1:
17826
                return ECC_BRAINPOOLP384R1_OID;
17827
            case WC_NID_brainpoolP512r1:
17828
                return ECC_BRAINPOOLP512R1_OID;
17829
            }
17830
            break;
17831
    #endif /* HAVE_ECC */
17832
17833
        /* oidBlkType */
17834
        case oidBlkType:
17835
            switch (nid) {
17836
            #ifdef WOLFSSL_AES_128
17837
                case AES128CBCb:
17838
                    return AES128CBCb;
17839
            #endif
17840
            #ifdef WOLFSSL_AES_192
17841
                case AES192CBCb:
17842
                    return AES192CBCb;
17843
            #endif
17844
            #ifdef WOLFSSL_AES_256
17845
                case AES256CBCb:
17846
                    return AES256CBCb;
17847
            #endif
17848
            #ifndef NO_DES3
17849
                case WC_NID_des:
17850
                    return DESb;
17851
                case WC_NID_des3:
17852
                    return DES3b;
17853
            #endif
17854
            }
17855
            break;
17856
17857
    #ifdef HAVE_OCSP
17858
        case oidOcspType:
17859
            switch (nid) {
17860
                case WC_NID_id_pkix_OCSP_basic:
17861
                    return OCSP_BASIC_OID;
17862
                case OCSP_NONCE_OID:
17863
                    return OCSP_NONCE_OID;
17864
            }
17865
            break;
17866
    #endif /* HAVE_OCSP */
17867
17868
        /* oidCertExtType */
17869
        case oidCertExtType:
17870
            switch (nid) {
17871
                case WC_NID_basic_constraints:
17872
                    return BASIC_CA_OID;
17873
                case WC_NID_subject_alt_name:
17874
                    return ALT_NAMES_OID;
17875
                case WC_NID_crl_distribution_points:
17876
                    return CRL_DIST_OID;
17877
                case WC_NID_info_access:
17878
                    return AUTH_INFO_OID;
17879
                case WC_NID_authority_key_identifier:
17880
                    return AUTH_KEY_OID;
17881
                case WC_NID_subject_key_identifier:
17882
                    return SUBJ_KEY_OID;
17883
                case WC_NID_inhibit_any_policy:
17884
                    return INHIBIT_ANY_OID;
17885
                case WC_NID_key_usage:
17886
                    return KEY_USAGE_OID;
17887
                case WC_NID_name_constraints:
17888
                    return NAME_CONS_OID;
17889
                case WC_NID_certificate_policies:
17890
                    return CERT_POLICY_OID;
17891
                case WC_NID_ext_key_usage:
17892
                    return EXT_KEY_USAGE_OID;
17893
            }
17894
            break;
17895
17896
        /* oidCertAuthInfoType */
17897
        case oidCertAuthInfoType:
17898
            switch (nid) {
17899
                case WC_NID_ad_OCSP:
17900
                    return AIA_OCSP_OID;
17901
                case WC_NID_ad_ca_issuers:
17902
                    return AIA_CA_ISSUER_OID;
17903
            }
17904
            break;
17905
17906
        /* oidCertPolicyType */
17907
        case oidCertPolicyType:
17908
            switch (nid) {
17909
                case WC_NID_any_policy:
17910
                    return CP_ANY_OID;
17911
            }
17912
            break;
17913
17914
        /* oidCertAltNameType */
17915
        case oidCertAltNameType:
17916
            switch (nid) {
17917
                case WC_NID_hw_name_oid:
17918
                    return HW_NAME_OID;
17919
            }
17920
            break;
17921
17922
        /* oidCertKeyUseType */
17923
        case oidCertKeyUseType:
17924
            switch (nid) {
17925
                case WC_NID_anyExtendedKeyUsage:
17926
                    return EKU_ANY_OID;
17927
                case EKU_SERVER_AUTH_OID:
17928
                    return EKU_SERVER_AUTH_OID;
17929
                case EKU_CLIENT_AUTH_OID:
17930
                    return EKU_CLIENT_AUTH_OID;
17931
                case EKU_OCSP_SIGN_OID:
17932
                    return EKU_OCSP_SIGN_OID;
17933
            }
17934
            break;
17935
17936
        /* oidKdfType */
17937
        case oidKdfType:
17938
            switch (nid) {
17939
                case PBKDF2_OID:
17940
                    return PBKDF2_OID;
17941
            }
17942
            break;
17943
17944
        /* oidPBEType */
17945
        case oidPBEType:
17946
            switch (nid) {
17947
                case PBE_SHA1_RC4_128:
17948
                    return PBE_SHA1_RC4_128;
17949
                case PBE_SHA1_DES:
17950
                    return PBE_SHA1_DES;
17951
                case PBE_SHA1_DES3:
17952
                    return PBE_SHA1_DES3;
17953
            }
17954
            break;
17955
17956
        /* oidKeyWrapType */
17957
        case oidKeyWrapType:
17958
            switch (nid) {
17959
            #ifdef WOLFSSL_AES_128
17960
                case AES128_WRAP:
17961
                    return AES128_WRAP;
17962
            #endif
17963
            #ifdef WOLFSSL_AES_192
17964
                case AES192_WRAP:
17965
                    return AES192_WRAP;
17966
            #endif
17967
            #ifdef WOLFSSL_AES_256
17968
                case AES256_WRAP:
17969
                    return AES256_WRAP;
17970
            #endif
17971
            }
17972
            break;
17973
17974
        /* oidCmsKeyAgreeType */
17975
        case oidCmsKeyAgreeType:
17976
            switch (nid) {
17977
                #ifndef NO_SHA
17978
                case dhSinglePass_stdDH_sha1kdf_scheme:
17979
                    return dhSinglePass_stdDH_sha1kdf_scheme;
17980
                #endif
17981
                #ifdef WOLFSSL_SHA224
17982
                case dhSinglePass_stdDH_sha224kdf_scheme:
17983
                    return dhSinglePass_stdDH_sha224kdf_scheme;
17984
                #endif
17985
                #ifndef NO_SHA256
17986
                case dhSinglePass_stdDH_sha256kdf_scheme:
17987
                    return dhSinglePass_stdDH_sha256kdf_scheme;
17988
                #endif
17989
                #ifdef WOLFSSL_SHA384
17990
                case dhSinglePass_stdDH_sha384kdf_scheme:
17991
                    return dhSinglePass_stdDH_sha384kdf_scheme;
17992
                #endif
17993
                #ifdef WOLFSSL_SHA512
17994
                case dhSinglePass_stdDH_sha512kdf_scheme:
17995
                    return dhSinglePass_stdDH_sha512kdf_scheme;
17996
                #endif
17997
            }
17998
            break;
17999
18000
        /* oidCmsKeyAgreeType */
18001
    #ifdef WOLFSSL_CERT_REQ
18002
        case oidCsrAttrType:
18003
            switch (nid) {
18004
                case WC_NID_pkcs9_contentType:
18005
                    return PKCS9_CONTENT_TYPE_OID;
18006
                case WC_NID_pkcs9_challengePassword:
18007
                    return CHALLENGE_PASSWORD_OID;
18008
                case WC_NID_serialNumber:
18009
                    return SERIAL_NUMBER_OID;
18010
                case WC_NID_userId:
18011
                    return USER_ID_OID;
18012
                case WC_NID_surname:
18013
                    return SURNAME_OID;
18014
            }
18015
            break;
18016
    #endif
18017
18018
        default:
18019
            WOLFSSL_MSG("NID not in table");
18020
            /* MSVC warns without the cast */
18021
            return (word32)-1;
18022
    }
18023
18024
    /* MSVC warns without the cast */
18025
    return (word32)-1;
18026
}
18027
18028
int oid2nid(word32 oid, int grp)
18029
{
18030
    size_t i;
18031
    /* get OID type */
18032
    switch (grp) {
18033
        /* oidHashType */
18034
        case oidHashType:
18035
            switch (oid) {
18036
            #ifdef WOLFSSL_MD2
18037
                case MD2h:
18038
                    return WC_NID_md2;
18039
            #endif
18040
            #ifndef NO_MD5
18041
                case MD5h:
18042
                    return WC_NID_md5;
18043
            #endif
18044
            #ifndef NO_SHA
18045
                case SHAh:
18046
                    return WC_NID_sha1;
18047
            #endif
18048
                case SHA224h:
18049
                    return WC_NID_sha224;
18050
            #ifndef NO_SHA256
18051
                case SHA256h:
18052
                    return WC_NID_sha256;
18053
            #endif
18054
            #ifdef WOLFSSL_SHA384
18055
                case SHA384h:
18056
                    return WC_NID_sha384;
18057
            #endif
18058
            #ifdef WOLFSSL_SHA512
18059
                case SHA512h:
18060
                    return WC_NID_sha512;
18061
            #endif
18062
            }
18063
            break;
18064
18065
        /*  oidSigType */
18066
        case oidSigType:
18067
            switch (oid) {
18068
            #ifndef NO_DSA
18069
                case CTC_SHAwDSA:
18070
                    return WC_NID_dsaWithSHA1;
18071
                case CTC_SHA256wDSA:
18072
                    return WC_NID_dsa_with_SHA256;
18073
            #endif /* NO_DSA */
18074
            #ifndef NO_RSA
18075
                case CTC_MD2wRSA:
18076
                    return WC_NID_md2WithRSAEncryption;
18077
                case CTC_MD5wRSA:
18078
                    return WC_NID_md5WithRSAEncryption;
18079
                case CTC_SHAwRSA:
18080
                    return WC_NID_sha1WithRSAEncryption;
18081
                case CTC_SHA224wRSA:
18082
                    return WC_NID_sha224WithRSAEncryption;
18083
                case CTC_SHA256wRSA:
18084
                    return WC_NID_sha256WithRSAEncryption;
18085
                case CTC_SHA384wRSA:
18086
                    return WC_NID_sha384WithRSAEncryption;
18087
                case CTC_SHA512wRSA:
18088
                    return WC_NID_sha512WithRSAEncryption;
18089
                #ifdef WOLFSSL_SHA3
18090
                case CTC_SHA3_224wRSA:
18091
                    return WC_NID_RSA_SHA3_224;
18092
                case CTC_SHA3_256wRSA:
18093
                    return WC_NID_RSA_SHA3_256;
18094
                case CTC_SHA3_384wRSA:
18095
                    return WC_NID_RSA_SHA3_384;
18096
                case CTC_SHA3_512wRSA:
18097
                    return WC_NID_RSA_SHA3_512;
18098
                #endif
18099
                #ifdef WC_RSA_PSS
18100
                case CTC_RSASSAPSS:
18101
                    return WC_NID_rsassaPss;
18102
                #endif
18103
            #endif /* NO_RSA */
18104
            #ifdef HAVE_ECC
18105
                case CTC_SHAwECDSA:
18106
                    return WC_NID_ecdsa_with_SHA1;
18107
                case CTC_SHA224wECDSA:
18108
                    return WC_NID_ecdsa_with_SHA224;
18109
                case CTC_SHA256wECDSA:
18110
                    return WC_NID_ecdsa_with_SHA256;
18111
                case CTC_SHA384wECDSA:
18112
                    return WC_NID_ecdsa_with_SHA384;
18113
                case CTC_SHA512wECDSA:
18114
                    return WC_NID_ecdsa_with_SHA512;
18115
                #ifdef WOLFSSL_SHA3
18116
                case CTC_SHA3_224wECDSA:
18117
                    return WC_NID_ecdsa_with_SHA3_224;
18118
                case CTC_SHA3_256wECDSA:
18119
                    return WC_NID_ecdsa_with_SHA3_256;
18120
                case CTC_SHA3_384wECDSA:
18121
                    return WC_NID_ecdsa_with_SHA3_384;
18122
                case CTC_SHA3_512wECDSA:
18123
                    return WC_NID_ecdsa_with_SHA3_512;
18124
                #endif
18125
            #endif /* HAVE_ECC */
18126
            }
18127
            break;
18128
18129
        /* oidKeyType */
18130
        case oidKeyType:
18131
            switch (oid) {
18132
            #ifndef NO_DSA
18133
                case DSAk:
18134
                    return WC_NID_dsa;
18135
            #endif /* NO_DSA */
18136
            #ifndef NO_RSA
18137
                case RSAk:
18138
                    return WC_NID_rsaEncryption;
18139
                #ifdef WC_RSA_PSS
18140
                case RSAPSSk:
18141
                    return WC_NID_rsassaPss;
18142
                #endif
18143
            #endif /* NO_RSA */
18144
            #ifdef HAVE_ECC
18145
                case ECDSAk:
18146
                    return WC_NID_X9_62_id_ecPublicKey;
18147
            #endif /* HAVE_ECC */
18148
            }
18149
            break;
18150
18151
18152
    #ifdef HAVE_ECC
18153
        case oidCurveType:
18154
            switch (oid) {
18155
            case ECC_SECP192R1_OID:
18156
                return WC_NID_X9_62_prime192v1;
18157
            case ECC_PRIME192V2_OID:
18158
                return WC_NID_X9_62_prime192v2;
18159
            case ECC_PRIME192V3_OID:
18160
                return WC_NID_X9_62_prime192v3;
18161
            case ECC_PRIME239V1_OID:
18162
                return WC_NID_X9_62_prime239v1;
18163
            case ECC_PRIME239V2_OID:
18164
                return WC_NID_X9_62_prime239v2;
18165
            case ECC_PRIME239V3_OID:
18166
                return WC_NID_X9_62_prime239v3;
18167
            case ECC_SECP256R1_OID:
18168
                return WC_NID_X9_62_prime256v1;
18169
            case ECC_SECP112R1_OID:
18170
                return WC_NID_secp112r1;
18171
            case ECC_SECP112R2_OID:
18172
                return WC_NID_secp112r2;
18173
            case ECC_SECP128R1_OID:
18174
                return WC_NID_secp128r1;
18175
            case ECC_SECP128R2_OID:
18176
                return WC_NID_secp128r2;
18177
            case ECC_SECP160R1_OID:
18178
                return WC_NID_secp160r1;
18179
            case ECC_SECP160R2_OID:
18180
                return WC_NID_secp160r2;
18181
            case ECC_SECP224R1_OID:
18182
                return WC_NID_secp224r1;
18183
            case ECC_SECP384R1_OID:
18184
                return WC_NID_secp384r1;
18185
            case ECC_SECP521R1_OID:
18186
                return WC_NID_secp521r1;
18187
            case ECC_SECP160K1_OID:
18188
                return WC_NID_secp160k1;
18189
            case ECC_SECP192K1_OID:
18190
                return WC_NID_secp192k1;
18191
            case ECC_SECP224K1_OID:
18192
                return WC_NID_secp224k1;
18193
            case ECC_SECP256K1_OID:
18194
                return WC_NID_secp256k1;
18195
            case ECC_BRAINPOOLP160R1_OID:
18196
                return WC_NID_brainpoolP160r1;
18197
            case ECC_BRAINPOOLP192R1_OID:
18198
                return WC_NID_brainpoolP192r1;
18199
            case ECC_BRAINPOOLP224R1_OID:
18200
                return WC_NID_brainpoolP224r1;
18201
            case ECC_BRAINPOOLP256R1_OID:
18202
                return WC_NID_brainpoolP256r1;
18203
            case ECC_BRAINPOOLP320R1_OID:
18204
                return WC_NID_brainpoolP320r1;
18205
            case ECC_BRAINPOOLP384R1_OID:
18206
                return WC_NID_brainpoolP384r1;
18207
            case ECC_BRAINPOOLP512R1_OID:
18208
                return WC_NID_brainpoolP512r1;
18209
            }
18210
            break;
18211
    #endif /* HAVE_ECC */
18212
18213
        /* oidBlkType */
18214
        case oidBlkType:
18215
            switch (oid) {
18216
            #ifdef WOLFSSL_AES_128
18217
                case AES128CBCb:
18218
                    return AES128CBCb;
18219
            #endif
18220
            #ifdef WOLFSSL_AES_192
18221
                case AES192CBCb:
18222
                    return AES192CBCb;
18223
            #endif
18224
            #ifdef WOLFSSL_AES_256
18225
                case AES256CBCb:
18226
                    return AES256CBCb;
18227
            #endif
18228
            #ifndef NO_DES3
18229
                case DESb:
18230
                    return WC_NID_des;
18231
                case DES3b:
18232
                    return WC_NID_des3;
18233
            #endif
18234
            }
18235
            break;
18236
18237
    #ifdef HAVE_OCSP
18238
        case oidOcspType:
18239
            switch (oid) {
18240
                case OCSP_BASIC_OID:
18241
                    return WC_NID_id_pkix_OCSP_basic;
18242
                case OCSP_NONCE_OID:
18243
                    return OCSP_NONCE_OID;
18244
            }
18245
            break;
18246
    #endif /* HAVE_OCSP */
18247
18248
        /* oidCertExtType */
18249
        case oidCertExtType:
18250
            switch (oid) {
18251
                case BASIC_CA_OID:
18252
                    return WC_NID_basic_constraints;
18253
                case ALT_NAMES_OID:
18254
                    return WC_NID_subject_alt_name;
18255
                case CRL_DIST_OID:
18256
                    return WC_NID_crl_distribution_points;
18257
                case AUTH_INFO_OID:
18258
                    return WC_NID_info_access;
18259
                case AUTH_KEY_OID:
18260
                    return WC_NID_authority_key_identifier;
18261
                case SUBJ_KEY_OID:
18262
                    return WC_NID_subject_key_identifier;
18263
                case INHIBIT_ANY_OID:
18264
                    return WC_NID_inhibit_any_policy;
18265
                case KEY_USAGE_OID:
18266
                    return WC_NID_key_usage;
18267
                case NAME_CONS_OID:
18268
                    return WC_NID_name_constraints;
18269
                case CERT_POLICY_OID:
18270
                    return WC_NID_certificate_policies;
18271
                case EXT_KEY_USAGE_OID:
18272
                    return WC_NID_ext_key_usage;
18273
            }
18274
            break;
18275
18276
        /* oidCertAuthInfoType */
18277
        case oidCertAuthInfoType:
18278
            switch (oid) {
18279
                case AIA_OCSP_OID:
18280
                    return WC_NID_ad_OCSP;
18281
                case AIA_CA_ISSUER_OID:
18282
                    return WC_NID_ad_ca_issuers;
18283
            }
18284
            break;
18285
18286
        /* oidCertPolicyType */
18287
        case oidCertPolicyType:
18288
            switch (oid) {
18289
                case CP_ANY_OID:
18290
                    return WC_NID_any_policy;
18291
            }
18292
            break;
18293
18294
        /* oidCertAltNameType */
18295
        case oidCertAltNameType:
18296
            switch (oid) {
18297
                case HW_NAME_OID:
18298
                    return WC_NID_hw_name_oid;
18299
            }
18300
            break;
18301
18302
        /* oidCertKeyUseType */
18303
        case oidCertKeyUseType:
18304
            switch (oid) {
18305
                case EKU_ANY_OID:
18306
                    return WC_NID_anyExtendedKeyUsage;
18307
                case EKU_SERVER_AUTH_OID:
18308
                    return EKU_SERVER_AUTH_OID;
18309
                case EKU_CLIENT_AUTH_OID:
18310
                    return EKU_CLIENT_AUTH_OID;
18311
                case EKU_OCSP_SIGN_OID:
18312
                    return EKU_OCSP_SIGN_OID;
18313
            }
18314
            break;
18315
18316
        /* oidKdfType */
18317
        case oidKdfType:
18318
            switch (oid) {
18319
                case PBKDF2_OID:
18320
                    return PBKDF2_OID;
18321
            }
18322
            break;
18323
18324
        /* oidPBEType */
18325
        case oidPBEType:
18326
            switch (oid) {
18327
                case PBE_SHA1_RC4_128:
18328
                    return PBE_SHA1_RC4_128;
18329
                case PBE_SHA1_DES:
18330
                    return PBE_SHA1_DES;
18331
                case PBE_SHA1_DES3:
18332
                    return PBE_SHA1_DES3;
18333
            }
18334
            break;
18335
18336
        /* oidKeyWrapType */
18337
        case oidKeyWrapType:
18338
            switch (oid) {
18339
            #ifdef WOLFSSL_AES_128
18340
                case AES128_WRAP:
18341
                    return AES128_WRAP;
18342
            #endif
18343
            #ifdef WOLFSSL_AES_192
18344
                case AES192_WRAP:
18345
                    return AES192_WRAP;
18346
            #endif
18347
            #ifdef WOLFSSL_AES_256
18348
                case AES256_WRAP:
18349
                    return AES256_WRAP;
18350
            #endif
18351
            }
18352
            break;
18353
18354
        /* oidCmsKeyAgreeType */
18355
        case oidCmsKeyAgreeType:
18356
            switch (oid) {
18357
                #ifndef NO_SHA
18358
                case dhSinglePass_stdDH_sha1kdf_scheme:
18359
                    return dhSinglePass_stdDH_sha1kdf_scheme;
18360
                #endif
18361
                #ifdef WOLFSSL_SHA224
18362
                case dhSinglePass_stdDH_sha224kdf_scheme:
18363
                    return dhSinglePass_stdDH_sha224kdf_scheme;
18364
                #endif
18365
                #ifndef NO_SHA256
18366
                case dhSinglePass_stdDH_sha256kdf_scheme:
18367
                    return dhSinglePass_stdDH_sha256kdf_scheme;
18368
                #endif
18369
                #ifdef WOLFSSL_SHA384
18370
                case dhSinglePass_stdDH_sha384kdf_scheme:
18371
                    return dhSinglePass_stdDH_sha384kdf_scheme;
18372
                #endif
18373
                #ifdef WOLFSSL_SHA512
18374
                case dhSinglePass_stdDH_sha512kdf_scheme:
18375
                    return dhSinglePass_stdDH_sha512kdf_scheme;
18376
                #endif
18377
            }
18378
            break;
18379
18380
#ifdef WOLFSSL_CERT_REQ
18381
        case oidCsrAttrType:
18382
            switch (oid) {
18383
                case PKCS9_CONTENT_TYPE_OID:
18384
                    return WC_NID_pkcs9_contentType;
18385
                case CHALLENGE_PASSWORD_OID:
18386
                    return WC_NID_pkcs9_challengePassword;
18387
                case SERIAL_NUMBER_OID:
18388
                    return WC_NID_serialNumber;
18389
                case USER_ID_OID:
18390
                    return WC_NID_userId;
18391
            }
18392
            break;
18393
#endif
18394
18395
        default:
18396
            WOLFSSL_MSG("OID not in table");
18397
    }
18398
    /* If not found in above switch then try the table */
18399
    for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
18400
        if (wolfssl_object_info[i].id == (int)oid) {
18401
            return wolfssl_object_info[i].nid;
18402
        }
18403
    }
18404
18405
    return WOLFSSL_FATAL_ERROR;
18406
}
18407
18408
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
18409
18410
#if defined(OPENSSL_EXTRA)
18411
18412
/* frees all nodes in the current threads error queue
18413
 *
18414
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
18415
 *     current threads queue will be free'd.
18416
 */
18417
void wolfSSL_ERR_remove_state(unsigned long id)
18418
{
18419
    WOLFSSL_ENTER("wolfSSL_ERR_remove_state");
18420
    (void)id;
18421
    if (wc_ERR_remove_state() != 0) {
18422
        WOLFSSL_MSG("Error with removing the state");
18423
    }
18424
}
18425
18426
#endif /* OPENSSL_EXTRA */
18427
18428
#ifdef WOLFSSL_STATIC_EPHEMERAL
18429
int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr)
18430
{
18431
    int ret;
18432
    word32 idx = 0;
18433
    DerBuffer* der = NULL;
18434
18435
    if (ssl == NULL || ssl->ctx == NULL || keyPtr == NULL) {
18436
        return BAD_FUNC_ARG;
18437
    }
18438
18439
#ifndef SINGLE_THREADED
18440
    if (!ssl->ctx->staticKELockInit) {
18441
        return BUFFER_E; /* no keys set */
18442
    }
18443
    ret = wc_LockMutex(&ssl->ctx->staticKELock);
18444
    if (ret != 0) {
18445
        return ret;
18446
    }
18447
#endif
18448
18449
    ret = BUFFER_E; /* set default error */
18450
    switch (keyAlgo) {
18451
    #ifndef NO_DH
18452
        case WC_PK_TYPE_DH:
18453
            if (ssl != NULL)
18454
                der = ssl->staticKE.dhKey;
18455
            if (der == NULL)
18456
                der = ssl->ctx->staticKE.dhKey;
18457
            if (der != NULL) {
18458
                DhKey* key = (DhKey*)keyPtr;
18459
                WOLFSSL_MSG("Using static DH key");
18460
                ret = wc_DhKeyDecode(der->buffer, &idx, key, der->length);
18461
            }
18462
            break;
18463
    #endif
18464
    #ifdef HAVE_ECC
18465
        case WC_PK_TYPE_ECDH:
18466
            if (ssl != NULL)
18467
                der = ssl->staticKE.ecKey;
18468
            if (der == NULL)
18469
                der = ssl->ctx->staticKE.ecKey;
18470
            if (der != NULL) {
18471
                ecc_key* key = (ecc_key*)keyPtr;
18472
                WOLFSSL_MSG("Using static ECDH key");
18473
                ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key,
18474
                    der->length);
18475
            }
18476
            break;
18477
    #endif
18478
    #ifdef HAVE_CURVE25519
18479
        case WC_PK_TYPE_CURVE25519:
18480
            if (ssl != NULL)
18481
                der = ssl->staticKE.x25519Key;
18482
            if (der == NULL)
18483
                der = ssl->ctx->staticKE.x25519Key;
18484
            if (der != NULL) {
18485
                curve25519_key* key = (curve25519_key*)keyPtr;
18486
                WOLFSSL_MSG("Using static X25519 key");
18487
18488
            #ifdef WOLFSSL_CURVE25519_BLINDING
18489
                ret = wc_curve25519_set_rng(key, ssl->rng);
18490
                if (ret == 0)
18491
            #endif
18492
                    ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key,
18493
                        der->length);
18494
            }
18495
            break;
18496
    #endif
18497
    #ifdef HAVE_CURVE448
18498
        case WC_PK_TYPE_CURVE448:
18499
            if (ssl != NULL)
18500
                der = ssl->staticKE.x448Key;
18501
            if (der == NULL)
18502
                der = ssl->ctx->staticKE.x448Key;
18503
            if (der != NULL) {
18504
                curve448_key* key = (curve448_key*)keyPtr;
18505
                WOLFSSL_MSG("Using static X448 key");
18506
                ret = wc_Curve448PrivateKeyDecode(der->buffer, &idx, key,
18507
                    der->length);
18508
            }
18509
            break;
18510
    #endif
18511
        default:
18512
            /* not supported */
18513
            ret = NOT_COMPILED_IN;
18514
            break;
18515
    }
18516
18517
#ifndef SINGLE_THREADED
18518
    wc_UnLockMutex(&ssl->ctx->staticKELock);
18519
#endif
18520
    return ret;
18521
}
18522
18523
static int SetStaticEphemeralKey(WOLFSSL_CTX* ctx,
18524
    StaticKeyExchangeInfo_t* staticKE, int keyAlgo, const char* key,
18525
    unsigned int keySz, int format, void* heap)
18526
{
18527
    int ret = 0;
18528
    DerBuffer* der = NULL;
18529
    byte* keyBuf = NULL;
18530
#ifndef NO_FILESYSTEM
18531
    const char* keyFile = NULL;
18532
#endif
18533
18534
    /* allow empty key to free buffer */
18535
    if (staticKE == NULL || (key == NULL && keySz > 0)) {
18536
        return BAD_FUNC_ARG;
18537
    }
18538
18539
    WOLFSSL_ENTER("SetStaticEphemeralKey");
18540
18541
    /* if just free'ing key then skip loading */
18542
    if (key != NULL) {
18543
    #ifndef NO_FILESYSTEM
18544
        /* load file from filesystem */
18545
        if (key != NULL && keySz == 0) {
18546
            size_t keyBufSz = 0;
18547
            keyFile = (const char*)key;
18548
            ret = wc_FileLoad(keyFile, &keyBuf, &keyBufSz, heap);
18549
            if (ret != 0) {
18550
                return ret;
18551
            }
18552
            keySz = (unsigned int)keyBufSz;
18553
        }
18554
        else
18555
    #endif
18556
        {
18557
            /* use as key buffer directly */
18558
            keyBuf = (byte*)key;
18559
        }
18560
18561
        if (format == WOLFSSL_FILETYPE_PEM) {
18562
        #ifdef WOLFSSL_PEM_TO_DER
18563
            int keyFormat = 0;
18564
            ret = PemToDer(keyBuf, keySz, PRIVATEKEY_TYPE, &der,
18565
                heap, NULL, &keyFormat);
18566
            /* auto detect key type */
18567
            if (ret == 0 && keyAlgo == WC_PK_TYPE_NONE) {
18568
                if (keyFormat == ECDSAk)
18569
                    keyAlgo = WC_PK_TYPE_ECDH;
18570
                else if (keyFormat == X25519k)
18571
                    keyAlgo = WC_PK_TYPE_CURVE25519;
18572
                else
18573
                    keyAlgo = WC_PK_TYPE_DH;
18574
            }
18575
        #else
18576
            ret = NOT_COMPILED_IN;
18577
        #endif
18578
        }
18579
        else {
18580
            /* Detect PK type (if required) */
18581
        #ifdef HAVE_ECC
18582
            if (keyAlgo == WC_PK_TYPE_NONE) {
18583
                word32 idx = 0;
18584
                ecc_key eccKey;
18585
                ret = wc_ecc_init_ex(&eccKey, heap, INVALID_DEVID);
18586
                if (ret == 0) {
18587
                    ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &eccKey, keySz);
18588
                    if (ret == 0)
18589
                        keyAlgo = WC_PK_TYPE_ECDH;
18590
                    wc_ecc_free(&eccKey);
18591
                }
18592
            }
18593
        #endif
18594
        #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
18595
            if (keyAlgo == WC_PK_TYPE_NONE) {
18596
                word32 idx = 0;
18597
                DhKey dhKey;
18598
                ret = wc_InitDhKey_ex(&dhKey, heap, INVALID_DEVID);
18599
                if (ret == 0) {
18600
                    ret = wc_DhKeyDecode(keyBuf, &idx, &dhKey, keySz);
18601
                    if (ret == 0)
18602
                        keyAlgo = WC_PK_TYPE_DH;
18603
                    wc_FreeDhKey(&dhKey);
18604
                }
18605
            }
18606
        #endif
18607
        #ifdef HAVE_CURVE25519
18608
            if (keyAlgo == WC_PK_TYPE_NONE) {
18609
                word32 idx = 0;
18610
                curve25519_key x25519Key;
18611
                ret = wc_curve25519_init_ex(&x25519Key, heap, INVALID_DEVID);
18612
                if (ret == 0) {
18613
                    ret = wc_Curve25519PrivateKeyDecode(keyBuf, &idx,
18614
                        &x25519Key, keySz);
18615
                    if (ret == 0)
18616
                        keyAlgo = WC_PK_TYPE_CURVE25519;
18617
                    wc_curve25519_free(&x25519Key);
18618
                }
18619
            }
18620
        #endif
18621
        #ifdef HAVE_CURVE448
18622
            if (keyAlgo == WC_PK_TYPE_NONE) {
18623
                word32 idx = 0;
18624
                curve448_key x448Key;
18625
                ret = wc_curve448_init(&x448Key);
18626
                if (ret == 0) {
18627
                    ret = wc_Curve448PrivateKeyDecode(keyBuf, &idx, &x448Key,
18628
                        keySz);
18629
                    if (ret == 0)
18630
                        keyAlgo = WC_PK_TYPE_CURVE448;
18631
                    wc_curve448_free(&x448Key);
18632
                }
18633
            }
18634
        #endif
18635
18636
            if (keyAlgo != WC_PK_TYPE_NONE) {
18637
                ret = AllocDer(&der, keySz, PRIVATEKEY_TYPE, heap);
18638
                if (ret == 0) {
18639
                    XMEMCPY(der->buffer, keyBuf, keySz);
18640
                }
18641
            }
18642
        }
18643
    }
18644
18645
#ifndef NO_FILESYSTEM
18646
    /* done with keyFile buffer */
18647
    if (keyFile && keyBuf) {
18648
        XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
18649
    }
18650
#endif
18651
18652
#ifndef SINGLE_THREADED
18653
    if (ret == 0 && !ctx->staticKELockInit) {
18654
        ret = wc_InitMutex(&ctx->staticKELock);
18655
        if (ret == 0) {
18656
            ctx->staticKELockInit = 1;
18657
        }
18658
    }
18659
#endif
18660
    if (ret == 0
18661
    #ifndef SINGLE_THREADED
18662
        && (ret = wc_LockMutex(&ctx->staticKELock)) == 0
18663
    #endif
18664
    ) {
18665
        switch (keyAlgo) {
18666
        #ifndef NO_DH
18667
            case WC_PK_TYPE_DH:
18668
                FreeDer(&staticKE->dhKey);
18669
                staticKE->dhKey = der; der = NULL;
18670
                break;
18671
        #endif
18672
        #ifdef HAVE_ECC
18673
            case WC_PK_TYPE_ECDH:
18674
                FreeDer(&staticKE->ecKey);
18675
                staticKE->ecKey = der; der = NULL;
18676
                break;
18677
        #endif
18678
        #ifdef HAVE_CURVE25519
18679
            case WC_PK_TYPE_CURVE25519:
18680
                FreeDer(&staticKE->x25519Key);
18681
                staticKE->x25519Key = der; der = NULL;
18682
                break;
18683
        #endif
18684
        #ifdef HAVE_CURVE448
18685
            case WC_PK_TYPE_CURVE448:
18686
                FreeDer(&staticKE->x448Key);
18687
                staticKE->x448Key = der; der = NULL;
18688
                break;
18689
        #endif
18690
            default:
18691
                /* not supported */
18692
                ret = NOT_COMPILED_IN;
18693
                break;
18694
        }
18695
18696
    #ifndef SINGLE_THREADED
18697
        wc_UnLockMutex(&ctx->staticKELock);
18698
    #endif
18699
    }
18700
18701
    if (ret != 0) {
18702
        FreeDer(&der);
18703
    }
18704
18705
    (void)ctx; /* not used for single threaded */
18706
18707
    WOLFSSL_LEAVE("SetStaticEphemeralKey", ret);
18708
18709
    return ret;
18710
}
18711
18712
int wolfSSL_CTX_set_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
18713
    const char* key, unsigned int keySz, int format)
18714
{
18715
    if (ctx == NULL) {
18716
        return BAD_FUNC_ARG;
18717
    }
18718
    return SetStaticEphemeralKey(ctx, &ctx->staticKE, keyAlgo,
18719
        key, keySz, format, ctx->heap);
18720
}
18721
int wolfSSL_set_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
18722
    const char* key, unsigned int keySz, int format)
18723
{
18724
    if (ssl == NULL || ssl->ctx == NULL) {
18725
        return BAD_FUNC_ARG;
18726
    }
18727
    return SetStaticEphemeralKey(ssl->ctx, &ssl->staticKE, keyAlgo,
18728
        key, keySz, format, ssl->heap);
18729
}
18730
18731
static int GetStaticEphemeralKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
18732
    int keyAlgo, const unsigned char** key, unsigned int* keySz)
18733
{
18734
    int ret = 0;
18735
    DerBuffer* der = NULL;
18736
18737
    if (key)   *key = NULL;
18738
    if (keySz) *keySz = 0;
18739
18740
#ifndef SINGLE_THREADED
18741
    if (ctx->staticKELockInit &&
18742
        (ret = wc_LockMutex(&ctx->staticKELock)) != 0) {
18743
        return ret;
18744
    }
18745
#endif
18746
18747
    switch (keyAlgo) {
18748
    #ifndef NO_DH
18749
        case WC_PK_TYPE_DH:
18750
            if (ssl != NULL)
18751
                der = ssl->staticKE.dhKey;
18752
            if (der == NULL)
18753
                der = ctx->staticKE.dhKey;
18754
            break;
18755
    #endif
18756
    #ifdef HAVE_ECC
18757
        case WC_PK_TYPE_ECDH:
18758
            if (ssl != NULL)
18759
                der = ssl->staticKE.ecKey;
18760
            if (der == NULL)
18761
                der = ctx->staticKE.ecKey;
18762
            break;
18763
    #endif
18764
    #ifdef HAVE_CURVE25519
18765
        case WC_PK_TYPE_CURVE25519:
18766
            if (ssl != NULL)
18767
                der = ssl->staticKE.x25519Key;
18768
            if (der == NULL)
18769
                der = ctx->staticKE.x25519Key;
18770
            break;
18771
    #endif
18772
    #ifdef HAVE_CURVE448
18773
        case WC_PK_TYPE_CURVE448:
18774
            if (ssl != NULL)
18775
                der = ssl->staticKE.x448Key;
18776
            if (der == NULL)
18777
                der = ctx->staticKE.x448Key;
18778
            break;
18779
    #endif
18780
        default:
18781
            /* not supported */
18782
            ret = NOT_COMPILED_IN;
18783
            break;
18784
    }
18785
18786
    if (der) {
18787
        if (key)
18788
            *key = der->buffer;
18789
        if (keySz)
18790
            *keySz = der->length;
18791
    }
18792
18793
#ifndef SINGLE_THREADED
18794
    wc_UnLockMutex(&ctx->staticKELock);
18795
#endif
18796
18797
    return ret;
18798
}
18799
18800
/* returns pointer to currently loaded static ephemeral as ASN.1 */
18801
/* this can be converted to PEM using wc_DerToPem */
18802
int wolfSSL_CTX_get_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
18803
    const unsigned char** key, unsigned int* keySz)
18804
{
18805
    if (ctx == NULL) {
18806
        return BAD_FUNC_ARG;
18807
    }
18808
18809
    return GetStaticEphemeralKey(ctx, NULL, keyAlgo, key, keySz);
18810
}
18811
int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
18812
    const unsigned char** key, unsigned int* keySz)
18813
{
18814
    if (ssl == NULL || ssl->ctx == NULL) {
18815
        return BAD_FUNC_ARG;
18816
    }
18817
18818
    return GetStaticEphemeralKey(ssl->ctx, ssl, keyAlgo, key, keySz);
18819
}
18820
18821
#endif /* WOLFSSL_STATIC_EPHEMERAL */
18822
18823
#if defined(OPENSSL_EXTRA)
18824
/* wolfSSL_THREADID_current is provided as a compat API with
18825
 * CRYPTO_THREADID_current to register current thread id into given id object.
18826
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
18827
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
18828
 * like as existing wolfSSL_THREADID_set_numeric.
18829
 */
18830
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
18831
{
18832
    (void)id;
18833
    return;
18834
}
18835
/* wolfSSL_THREADID_hash is provided as a compatible API with
18836
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
18837
 * specified thread id. However, CRYPTO_THREADID_hash API has been
18838
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
18839
 * This API only works as a stub to returns 0. This behavior is
18840
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
18841
 */
18842
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
18843
{
18844
    (void)id;
18845
    return 0UL;
18846
}
18847
/* wolfSSL_set_ecdh_auto is provided as compatible API with
18848
 * SSL_set_ecdh_auto to enable auto ecdh curve selection functionality.
18849
 * Since this functionality is enabled by default in wolfSSL,
18850
 * this API exists as a stub.
18851
 */
18852
int wolfSSL_set_ecdh_auto(WOLFSSL* ssl, int onoff)
18853
{
18854
    (void)ssl;
18855
    (void)onoff;
18856
    return WOLFSSL_SUCCESS;
18857
}
18858
/* wolfSSL_CTX_set_ecdh_auto is provided as compatible API with
18859
 * SSL_CTX_set_ecdh_auto to enable auto ecdh curve selection functionality.
18860
 * Since this functionality is enabled by default in wolfSSL,
18861
 * this API exists as a stub.
18862
 */
18863
int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff)
18864
{
18865
    (void)ctx;
18866
    (void)onoff;
18867
    return WOLFSSL_SUCCESS;
18868
}
18869
18870
/* wolfSSL_CTX_set_dh_auto is provided as compatible API with
18871
 * SSL_CTX_set_dh_auto to enable auto dh selection functionality.
18872
 * Since this functionality is enabled by default in wolfSSL,
18873
 * this API exists as a stub.
18874
 */
18875
int wolfSSL_CTX_set_dh_auto(WOLFSSL_CTX* ctx, int onoff)
18876
{
18877
    (void)ctx;
18878
    (void)onoff;
18879
    return WOLFSSL_SUCCESS;
18880
}
18881
18882
/**
18883
 * Set security level (wolfSSL doesn't support setting the security level).
18884
 *
18885
 * The security level can only be set through a system wide crypto-policy
18886
 * with wolfSSL_crypto_policy_enable().
18887
 *
18888
 * @param ctx  a pointer to WOLFSSL_CTX structure
18889
 * @param level security level
18890
 */
18891
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
18892
{
18893
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
18894
    (void)ctx;
18895
    (void)level;
18896
}
18897
18898
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
18899
{
18900
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
18901
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
18902
    if (ctx == NULL) {
18903
        return BAD_FUNC_ARG;
18904
    }
18905
18906
    return ctx->secLevel;
18907
    #else
18908
    (void)ctx;
18909
    return 0;
18910
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
18911
}
18912
18913
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
18914
/*
18915
 * This API accepts a user callback which puts key-log records into
18916
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
18917
 * each SSL object on its creation timing.
18918
 */
18919
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
18920
    wolfSSL_CTX_keylog_cb_func cb)
18921
{
18922
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
18923
    /* stores the callback into WOLFSSL_CTX */
18924
    if (ctx != NULL) {
18925
        ctx->keyLogCb = cb;
18926
    }
18927
}
18928
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
18929
    const WOLFSSL_CTX* ctx)
18930
{
18931
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
18932
    if (ctx != NULL)
18933
        return ctx->keyLogCb;
18934
    return NULL;
18935
}
18936
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
18937
18938
#endif /* OPENSSL_EXTRA */
18939
18940
#ifdef WOLFSSL_THREADED_CRYPT
18941
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
18942
{
18943
    ThreadCrypt* encrypt;
18944
18945
    if (ssl == NULL) {
18946
        return 0;
18947
    }
18948
18949
    encrypt = &ssl->buffers.encrypt[idx];
18950
    return (encrypt->avail == 0) && (encrypt->done == 0);
18951
}
18952
18953
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
18954
{
18955
    ThreadCrypt* encrypt;
18956
18957
    if (ssl == NULL) {
18958
        return 1;
18959
    }
18960
18961
    encrypt = &ssl->buffers.encrypt[idx];
18962
    return encrypt->stop;
18963
}
18964
18965
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
18966
{
18967
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
18968
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
18969
18970
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
18971
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
18972
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
18973
        word32 encSz = encrypt->buffer.length - encrypt->offset;
18974
18975
        ret =
18976
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
18977
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
18978
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
18979
              wc_AesGcmEncrypt_ex
18980
#else
18981
              wc_AesGcmEncrypt
18982
#endif
18983
              (encrypt->encrypt.aes,
18984
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
18985
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
18986
               encrypt->nonce, AESGCM_NONCE_SZ,
18987
               out + encSz - ssl->specs.aead_mac_size,
18988
               ssl->specs.aead_mac_size,
18989
               encrypt->additional, AEAD_AUTH_DATA_SZ);
18990
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
18991
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
18992
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
18993
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
18994
#endif
18995
        encrypt->done = 1;
18996
    }
18997
18998
    return ret;
18999
}
19000
19001
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
19002
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
19003
{
19004
    int ret = 0;
19005
19006
    if (ssl == NULL) {
19007
        ret = BAD_FUNC_ARG;
19008
    }
19009
    else {
19010
        ssl->buffers.encrypt[idx].signal = signal;
19011
        ssl->buffers.encrypt[idx].signalCtx = ctx;
19012
    }
19013
19014
    return ret;
19015
}
19016
#endif
19017
19018
19019
#ifndef NO_CERT
19020
#define WOLFSSL_X509_INCLUDED
19021
#include "src/x509.c"
19022
#endif
19023
19024
/*******************************************************************************
19025
 * START OF standard C library wrapping APIs
19026
 ******************************************************************************/
19027
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
19028
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
19029
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
19030
     defined(WOLFSSL_OPENSSH)))
19031
#ifndef NO_WOLFSSL_STUB
19032
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
19033
                                void *(*r) (void *, size_t, const char *,
19034
                                            int), void (*f) (void *))
19035
{
19036
    (void) m;
19037
    (void) r;
19038
    (void) f;
19039
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
19040
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
19041
19042
    return WOLFSSL_FAILURE;
19043
}
19044
#endif
19045
#endif
19046
19047
#if defined(OPENSSL_EXTRA)
19048
19049
/**
19050
 * free allocated memory resource
19051
 * @param str  a pointer to resource to be freed
19052
 * @param file dummy argument
19053
 * @param line dummy argument
19054
 */
19055
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
19056
{
19057
    (void)file;
19058
    (void)line;
19059
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
19060
}
19061
/**
19062
 * allocate memory with size of num
19063
 * @param num  size of memory allocation to be malloced
19064
 * @param file dummy argument
19065
 * @param line dummy argument
19066
 * @return a pointer to allocated memory on succssesful, otherwise NULL
19067
 */
19068
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
19069
{
19070
    (void)file;
19071
    (void)line;
19072
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
19073
}
19074
19075
#endif
19076
19077
/*******************************************************************************
19078
 * END OF standard C library wrapping APIs
19079
 ******************************************************************************/
19080
19081
/*******************************************************************************
19082
 * START OF EX_DATA APIs
19083
 ******************************************************************************/
19084
#ifdef HAVE_EX_DATA
19085
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
19086
{
19087
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
19088
}
19089
19090
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
19091
{
19092
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
19093
#ifdef MAX_EX_DATA
19094
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
19095
        return ex_data->ex_data[idx];
19096
    }
19097
#else
19098
    (void)ex_data;
19099
    (void)idx;
19100
#endif
19101
    return NULL;
19102
}
19103
19104
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
19105
    void *data)
19106
{
19107
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
19108
#ifdef MAX_EX_DATA
19109
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
19110
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
19111
        if (ex_data->ex_data_cleanup_routines[idx]) {
19112
            /* call cleanup then remove cleanup callback,
19113
             * since different value is being set */
19114
            if (ex_data->ex_data[idx])
19115
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
19116
            ex_data->ex_data_cleanup_routines[idx] = NULL;
19117
        }
19118
#endif
19119
        ex_data->ex_data[idx] = data;
19120
        return WOLFSSL_SUCCESS;
19121
    }
19122
#else
19123
    (void)ex_data;
19124
    (void)idx;
19125
    (void)data;
19126
#endif
19127
    return WOLFSSL_FAILURE;
19128
}
19129
19130
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
19131
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
19132
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
19133
    int idx,
19134
    void *data,
19135
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
19136
{
19137
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
19138
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
19139
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
19140
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
19141
        ex_data->ex_data[idx] = data;
19142
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
19143
        return WOLFSSL_SUCCESS;
19144
    }
19145
    return WOLFSSL_FAILURE;
19146
}
19147
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
19148
#endif /* HAVE_EX_DATA */
19149
19150
#ifdef HAVE_EX_DATA_CRYPTO
19151
/**
19152
 * Issues unique index for the class specified by class_index.
19153
 * Other parameter except class_index are ignored.
19154
 * Currently, following class_index are accepted:
19155
 *  - WOLF_CRYPTO_EX_INDEX_SSL
19156
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
19157
 *  - WOLF_CRYPTO_EX_INDEX_X509
19158
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
19159
 * @param argp  parameters to be saved
19160
 * @param argl  parameters to be saved
19161
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
19162
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
19163
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
19164
 * @return index value grater or equal to zero on success, -1 on failure.
19165
 */
19166
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
19167
                                           WOLFSSL_CRYPTO_EX_new* new_func,
19168
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
19169
                                           WOLFSSL_CRYPTO_EX_free* free_func)
19170
{
19171
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
19172
19173
    return wolfssl_get_ex_new_index(class_index, argl, argp, new_func,
19174
            dup_func, free_func);
19175
}
19176
#endif /* HAVE_EX_DATA_CRYPTO */
19177
19178
/*******************************************************************************
19179
 * END OF EX_DATA APIs
19180
 ******************************************************************************/
19181
19182
/*******************************************************************************
19183
 * START OF BUF_MEM API
19184
 ******************************************************************************/
19185
19186
#if defined(OPENSSL_EXTRA)
19187
19188
/* Begin functions for openssl/buffer.h */
19189
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
19190
{
19191
    WOLFSSL_BUF_MEM* buf;
19192
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
19193
                                                        DYNAMIC_TYPE_OPENSSL);
19194
    if (buf) {
19195
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
19196
    }
19197
    return buf;
19198
}
19199
19200
/* non-compat API returns length of buffer on success */
19201
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
19202
        char zeroFill)
19203
{
19204
19205
    int len_int = (int)len;
19206
    int mx;
19207
    char* tmp;
19208
19209
    /* verify provided arguments */
19210
    if (buf == NULL || len_int < 0) {
19211
        return 0; /* BAD_FUNC_ARG; */
19212
    }
19213
19214
    /* check to see if fits in existing length */
19215
    if (buf->length > len) {
19216
        buf->length = len;
19217
        return len_int;
19218
    }
19219
19220
    /* check to see if fits in max buffer */
19221
    if (buf->max >= len) {
19222
        if (buf->data != NULL && zeroFill) {
19223
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
19224
        }
19225
        buf->length = len;
19226
        return len_int;
19227
    }
19228
19229
    /* expand size, to handle growth */
19230
    mx = (len_int + 3) / 3 * 4;
19231
19232
#ifdef WOLFSSL_NO_REALLOC
19233
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
19234
    if (tmp != NULL && buf->data != NULL) {
19235
       XMEMCPY(tmp, buf->data, len_int);
19236
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
19237
       buf->data = NULL;
19238
    }
19239
#else
19240
    /* use realloc */
19241
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
19242
#endif
19243
19244
    if (tmp == NULL) {
19245
        return 0; /* ERR_R_MALLOC_FAILURE; */
19246
    }
19247
    buf->data = tmp;
19248
19249
    buf->max = (size_t)mx;
19250
    if (zeroFill)
19251
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
19252
    buf->length = len;
19253
19254
    return len_int;
19255
19256
}
19257
19258
/* returns length of buffer on success */
19259
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
19260
{
19261
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
19262
}
19263
19264
/* non-compat API returns length of buffer on success */
19265
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
19266
{
19267
    char* tmp;
19268
    int mx;
19269
19270
    /* verify provided arguments */
19271
    if (buf == NULL || len == 0 || (int)len <= 0) {
19272
        return 0; /* BAD_FUNC_ARG; */
19273
    }
19274
19275
    if (len == buf->length)
19276
        return (int)len;
19277
19278
    if (len > buf->length)
19279
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
19280
19281
    /* expand size, to handle growth */
19282
    mx = ((int)len + 3) / 3 * 4;
19283
19284
    /* We want to shrink the internal buffer */
19285
#ifdef WOLFSSL_NO_REALLOC
19286
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
19287
    if (tmp != NULL && buf->data != NULL)
19288
    {
19289
        XMEMCPY(tmp, buf->data, len);
19290
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
19291
        buf->data = NULL;
19292
    }
19293
#else
19294
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
19295
#endif
19296
19297
    if (tmp == NULL)
19298
        return 0;
19299
19300
    buf->data = tmp;
19301
    buf->length = len;
19302
    buf->max = (size_t)mx;
19303
19304
    return (int)len;
19305
}
19306
19307
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
19308
{
19309
    if (buf) {
19310
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
19311
        buf->data = NULL;
19312
        buf->max = 0;
19313
        buf->length = 0;
19314
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
19315
    }
19316
}
19317
/* End Functions for openssl/buffer.h */
19318
19319
#endif /* OPENSSL_EXTRA */
19320
19321
/*******************************************************************************
19322
 * END OF BUF_MEM API
19323
 ******************************************************************************/
19324
19325
#define WOLFSSL_CONF_INCLUDED
19326
#include <src/conf.c>
19327
19328
/*******************************************************************************
19329
 * START OF RAND API
19330
 ******************************************************************************/
19331
19332
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
19333
static int wolfSSL_RAND_InitMutex(void)
19334
{
19335
#ifndef WOLFSSL_MUTEX_INITIALIZER
19336
    if (gRandMethodsInit == 0) {
19337
        if (wc_InitMutex(&gRandMethodMutex) != 0) {
19338
            WOLFSSL_MSG("Bad Init Mutex rand methods");
19339
            return BAD_MUTEX_E;
19340
        }
19341
        gRandMethodsInit = 1;
19342
    }
19343
#endif
19344
    return 0;
19345
}
19346
#endif
19347
19348
#ifdef OPENSSL_EXTRA
19349
19350
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
19351
    ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST))
19352
/* In older FIPS bundles add check for reseed here since it does not exist in
19353
 * the older random.c certified files. */
19354
static pid_t currentRandPid = 0;
19355
#endif
19356
19357
/* Checks if the global RNG has been created. If not then one is created.
19358
 *
19359
 * Returns WOLFSSL_SUCCESS when no error is encountered.
19360
 */
19361
int wolfSSL_RAND_Init(void)
19362
{
19363
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
19364
#ifdef HAVE_GLOBAL_RNG
19365
    if (wc_LockMutex(&globalRNGMutex) == 0) {
19366
        if (initGlobalRNG == 0) {
19367
            ret = wc_InitRng(&globalRNG);
19368
            if (ret == 0) {
19369
            #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
19370
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
19371
                 defined(HAVE_SELFTEST))
19372
19373
                currentRandPid = getpid();
19374
            #endif
19375
                initGlobalRNG = 1;
19376
                ret = WOLFSSL_SUCCESS;
19377
            }
19378
        }
19379
        else {
19380
            /* GlobalRNG is already initialized */
19381
            ret = WOLFSSL_SUCCESS;
19382
        }
19383
19384
        wc_UnLockMutex(&globalRNGMutex);
19385
    }
19386
#endif
19387
    return ret;
19388
}
19389
19390
19391
/* WOLFSSL_SUCCESS on ok */
19392
int wolfSSL_RAND_seed(const void* seed, int len)
19393
{
19394
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19395
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
19396
        if (gRandMethods && gRandMethods->seed) {
19397
            int ret = gRandMethods->seed(seed, len);
19398
            wc_UnLockMutex(&gRandMethodMutex);
19399
            return ret;
19400
        }
19401
        wc_UnLockMutex(&gRandMethodMutex);
19402
    }
19403
#else
19404
    (void)seed;
19405
    (void)len;
19406
#endif
19407
19408
    /* Make sure global shared RNG (globalRNG) is initialized */
19409
    return wolfSSL_RAND_Init();
19410
}
19411
19412
19413
/* Returns the path for reading seed data from.
19414
 * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
19415
 *
19416
 * Note uses stdlib by default unless XGETENV macro is overwritten
19417
 *
19418
 * fname buffer to hold path
19419
 * len   length of fname buffer
19420
 *
19421
 * Returns a pointer to fname on success and NULL on failure
19422
 */
19423
const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
19424
{
19425
#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV)
19426
    char* rt;
19427
19428
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
19429
19430
    if (fname == NULL) {
19431
        return NULL;
19432
    }
19433
19434
    XMEMSET(fname, 0, len);
19435
19436
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
19437
    if ((rt = XGETENV("RANDFILE")) != NULL) {
19438
        if (len > XSTRLEN(rt)) {
19439
            XMEMCPY(fname, rt, XSTRLEN(rt));
19440
        }
19441
        else {
19442
            WOLFSSL_MSG("RANDFILE too large for buffer");
19443
            rt = NULL;
19444
        }
19445
    }
19446
/* // NOLINTEND(concurrency-mt-unsafe) */
19447
19448
    /* $RANDFILE was not set or is too large, check $HOME */
19449
    if (rt == NULL) {
19450
        const char ap[] = "/.rnd";
19451
19452
        WOLFSSL_MSG("Environment variable RANDFILE not set");
19453
19454
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
19455
        if ((rt = XGETENV("HOME")) == NULL) {
19456
            #ifdef XALTHOMEVARNAME
19457
            if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) {
19458
                WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME
19459
                            " not set");
19460
                return NULL;
19461
            }
19462
            #else
19463
            WOLFSSL_MSG("Environment variable HOME not set");
19464
            return NULL;
19465
            #endif
19466
        }
19467
/* // NOLINTEND(concurrency-mt-unsafe) */
19468
19469
        if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
19470
            fname[0] = '\0';
19471
            XSTRNCAT(fname, rt, len);
19472
            XSTRNCAT(fname, ap, len - XSTRLEN(rt));
19473
            return fname;
19474
        }
19475
        else {
19476
            WOLFSSL_MSG("Path too large for buffer");
19477
            return NULL;
19478
        }
19479
    }
19480
19481
    return fname;
19482
#else
19483
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
19484
    WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, "
19485
                "not compiled in");
19486
    (void)fname;
19487
    (void)len;
19488
    return NULL;
19489
#endif
19490
}
19491
19492
19493
/* Writes 1024 bytes from the RNG to the given file name.
19494
 *
19495
 * fname name of file to write to
19496
 *
19497
 * Returns the number of bytes written
19498
 */
19499
int wolfSSL_RAND_write_file(const char* fname)
19500
{
19501
    int bytes = 0;
19502
19503
    WOLFSSL_ENTER("wolfSSL_RAND_write_file");
19504
19505
    if (fname == NULL) {
19506
        return WOLFSSL_FAILURE;
19507
    }
19508
19509
#ifndef NO_FILESYSTEM
19510
    {
19511
    #ifndef WOLFSSL_SMALL_STACK
19512
        unsigned char buf[1024];
19513
    #else
19514
        unsigned char* buf = (unsigned char *)XMALLOC(1024, NULL,
19515
                                                       DYNAMIC_TYPE_TMP_BUFFER);
19516
        if (buf == NULL) {
19517
            WOLFSSL_MSG("malloc failed");
19518
            return WOLFSSL_FAILURE;
19519
        }
19520
    #endif
19521
        bytes = 1024; /* default size of buf */
19522
19523
        if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
19524
            WOLFSSL_MSG("No RNG to use");
19525
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19526
            return 0;
19527
        }
19528
19529
        if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) {
19530
            WOLFSSL_MSG("Error generating random buffer");
19531
            bytes = 0;
19532
        }
19533
        else {
19534
            XFILE f;
19535
19536
        #ifdef WOLFSSL_CHECK_MEM_ZERO
19537
            wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
19538
        #endif
19539
19540
            f = XFOPEN(fname, "wb");
19541
            if (f == XBADFILE) {
19542
                WOLFSSL_MSG("Error opening the file");
19543
                bytes = 0;
19544
            }
19545
            else {
19546
                size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f);
19547
                bytes = (int)bytes_written;
19548
                XFCLOSE(f);
19549
            }
19550
        }
19551
        ForceZero(buf, (word32)bytes);
19552
    #ifdef WOLFSSL_SMALL_STACK
19553
        XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19554
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
19555
        wc_MemZero_Check(buf, sizeof(buf));
19556
    #endif
19557
    }
19558
#endif
19559
19560
    return bytes;
19561
}
19562
19563
#ifndef FREERTOS_TCP
19564
19565
/* These constant values are protocol values made by egd */
19566
#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \
19567
    !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \
19568
    defined(HAVE_SYS_UN_H)
19569
    #define WOLFSSL_EGD_NBLOCK 0x01
19570
    #include <sys/un.h>
19571
#endif
19572
19573
/* This collects entropy from the path nm and seeds the global PRNG with it.
19574
 *
19575
 * nm is the file path to the egd server
19576
 *
19577
 * Returns the number of bytes read.
19578
 */
19579
int wolfSSL_RAND_egd(const char* nm)
19580
{
19581
#ifdef WOLFSSL_EGD_NBLOCK
19582
    struct sockaddr_un rem;
19583
    int fd;
19584
    int ret = WOLFSSL_SUCCESS;
19585
    word32 bytes = 0;
19586
    word32 idx   = 0;
19587
#ifndef WOLFSSL_SMALL_STACK
19588
    unsigned char buf[256];
19589
#else
19590
    unsigned char* buf;
19591
    buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19592
    if (buf == NULL) {
19593
        WOLFSSL_MSG("Not enough memory");
19594
        return WOLFSSL_FATAL_ERROR;
19595
    }
19596
#endif
19597
19598
    XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
19599
    if (nm == NULL) {
19600
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19601
        return WOLFSSL_FATAL_ERROR;
19602
    }
19603
19604
    fd = socket(AF_UNIX, SOCK_STREAM, 0);
19605
    if (fd < 0) {
19606
        WOLFSSL_MSG("Error creating socket");
19607
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19608
        return WOLFSSL_FATAL_ERROR;
19609
    }
19610
    rem.sun_family = AF_UNIX;
19611
    XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
19612
    rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
19613
19614
    /* connect to egd server */
19615
    if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
19616
        WOLFSSL_MSG("error connecting to egd server");
19617
        ret = WOLFSSL_FATAL_ERROR;
19618
    }
19619
19620
#ifdef WOLFSSL_CHECK_MEM_ZERO
19621
    if (ret == WOLFSSL_SUCCESS) {
19622
        wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
19623
    }
19624
#endif
19625
    while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
19626
        buf[idx]     = WOLFSSL_EGD_NBLOCK;
19627
        buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
19628
        ret = (int)write(fd, buf + idx, 2);
19629
        if (ret != 2) {
19630
            if (errno == EAGAIN) {
19631
                ret = WOLFSSL_SUCCESS;
19632
                continue;
19633
            }
19634
            WOLFSSL_MSG("error requesting entropy from egd server");
19635
            ret = WOLFSSL_FATAL_ERROR;
19636
            break;
19637
        }
19638
19639
        /* attempting to read */
19640
        buf[idx] = 0;
19641
        ret = (int)read(fd, buf + idx, 256 - bytes);
19642
        if (ret == 0) {
19643
            WOLFSSL_MSG("error reading entropy from egd server");
19644
            ret = WOLFSSL_FATAL_ERROR;
19645
            break;
19646
        }
19647
        if (ret > 0 && buf[idx] > 0) {
19648
            bytes += buf[idx]; /* egd stores amount sent in first byte */
19649
            if (bytes + idx > 255 || buf[idx] > ret) {
19650
                WOLFSSL_MSG("Buffer error");
19651
                ret = WOLFSSL_FATAL_ERROR;
19652
                break;
19653
            }
19654
            XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
19655
            idx = bytes;
19656
            ret = WOLFSSL_SUCCESS;
19657
            if (bytes >= 255) {
19658
                break;
19659
            }
19660
        }
19661
        else {
19662
            if (errno == EAGAIN || errno == EINTR) {
19663
                WOLFSSL_MSG("EGD would read");
19664
                ret = WOLFSSL_SUCCESS; /* try again */
19665
            }
19666
            else if (buf[idx] == 0) {
19667
                /* if egd returned 0 then there is no more entropy to be had.
19668
                   Do not try more reads. */
19669
                ret = WOLFSSL_SUCCESS;
19670
                break;
19671
            }
19672
            else {
19673
                WOLFSSL_MSG("Error with read");
19674
                ret = WOLFSSL_FATAL_ERROR;
19675
            }
19676
        }
19677
    }
19678
19679
    if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
19680
        /* call to check global RNG is created */
19681
        if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
19682
            WOLFSSL_MSG("Error with initializing global RNG structure");
19683
            ret = WOLFSSL_FATAL_ERROR;
19684
        }
19685
        else if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
19686
                != 0) {
19687
            WOLFSSL_MSG("Error with reseeding DRBG structure");
19688
            ret = WOLFSSL_FATAL_ERROR;
19689
        }
19690
        #ifdef SHOW_SECRETS
19691
        else { /* print out entropy found only when no error occurred */
19692
            word32 i;
19693
            printf("EGD Entropy = ");
19694
            for (i = 0; i < bytes; i++) {
19695
                printf("%02X", buf[i]);
19696
            }
19697
            printf("\n");
19698
        }
19699
        #endif
19700
    }
19701
19702
    ForceZero(buf, bytes);
19703
#ifdef WOLFSSL_SMALL_STACK
19704
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19705
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
19706
    wc_MemZero_Check(buf, 256);
19707
#endif
19708
    close(fd);
19709
19710
    if (ret == WOLFSSL_SUCCESS) {
19711
        return (int)bytes;
19712
    }
19713
    else {
19714
        return ret;
19715
    }
19716
#else
19717
    WOLFSSL_MSG("Type of socket needed is not available");
19718
    WOLFSSL_MSG("\tor using mode where DRBG API is not available");
19719
    (void)nm;
19720
19721
    return WOLFSSL_FATAL_ERROR;
19722
#endif /* WOLFSSL_EGD_NBLOCK */
19723
}
19724
19725
#endif /* !FREERTOS_TCP */
19726
19727
void wolfSSL_RAND_Cleanup(void)
19728
{
19729
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19730
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
19731
        if (gRandMethods && gRandMethods->cleanup)
19732
            gRandMethods->cleanup();
19733
        wc_UnLockMutex(&gRandMethodMutex);
19734
    }
19735
19736
    #ifndef WOLFSSL_MUTEX_INITIALIZER
19737
    if (wc_FreeMutex(&gRandMethodMutex) == 0)
19738
        gRandMethodsInit = 0;
19739
    #endif
19740
#endif
19741
#ifdef HAVE_GLOBAL_RNG
19742
    if (wc_LockMutex(&globalRNGMutex) == 0) {
19743
        if (initGlobalRNG) {
19744
            wc_FreeRng(&globalRNG);
19745
            initGlobalRNG = 0;
19746
        }
19747
        wc_UnLockMutex(&globalRNGMutex);
19748
    }
19749
#endif
19750
}
19751
19752
/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise
19753
 * WOLFSSL_FAILURE */
19754
int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
19755
{
19756
    int ret;
19757
    int hash;
19758
    byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */
19759
19760
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19761
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
19762
        if (gRandMethods && gRandMethods->pseudorand) {
19763
            ret = gRandMethods->pseudorand(buf, num);
19764
            wc_UnLockMutex(&gRandMethodMutex);
19765
            return ret;
19766
        }
19767
        wc_UnLockMutex(&gRandMethodMutex);
19768
    }
19769
#endif
19770
19771
#ifdef WOLFSSL_HAVE_PRF
19772
    #ifndef NO_SHA256
19773
    hash = WC_SHA256;
19774
    #elif defined(WOLFSSL_SHA384)
19775
    hash = WC_SHA384;
19776
    #elif !defined(NO_SHA)
19777
    hash = WC_SHA;
19778
    #elif !defined(NO_MD5)
19779
    hash = WC_MD5;
19780
    #endif
19781
19782
    /* get secret value from source of entropy */
19783
    ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
19784
19785
    /* uses input buffer to seed for pseudo random number generation, each
19786
     * thread will potentially have different results this way */
19787
    if (ret == WOLFSSL_SUCCESS) {
19788
        PRIVATE_KEY_UNLOCK();
19789
        ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
19790
                hash, NULL, INVALID_DEVID);
19791
        PRIVATE_KEY_LOCK();
19792
        ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
19793
    }
19794
#else
19795
    /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
19796
    ret = wolfSSL_RAND_bytes(buf, num);
19797
    (void)hash;
19798
    (void)secret;
19799
#endif
19800
    return ret;
19801
}
19802
19803
/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0
19804
 * on failure */
19805
int wolfSSL_RAND_bytes(unsigned char* buf, int num)
19806
{
19807
    int     ret = 0;
19808
    WC_RNG* rng = NULL;
19809
    WC_DECLARE_VAR(tmpRNG, WC_RNG, 1, 0);
19810
    int initTmpRng = 0;
19811
#ifdef HAVE_GLOBAL_RNG
19812
    int used_global = 0;
19813
#endif
19814
19815
    WOLFSSL_ENTER("wolfSSL_RAND_bytes");
19816
    /* sanity check */
19817
    if (buf == NULL || num < 0)
19818
        /* return code compliant with OpenSSL */
19819
        return 0;
19820
19821
    /* if a RAND callback has been set try and use it */
19822
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19823
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
19824
        if (gRandMethods && gRandMethods->bytes) {
19825
            ret = gRandMethods->bytes(buf, num);
19826
            wc_UnLockMutex(&gRandMethodMutex);
19827
            return ret;
19828
        }
19829
        wc_UnLockMutex(&gRandMethodMutex);
19830
    }
19831
#endif
19832
#ifdef HAVE_GLOBAL_RNG
19833
    if (initGlobalRNG) {
19834
        if (wc_LockMutex(&globalRNGMutex) != 0) {
19835
            WOLFSSL_MSG("Bad Lock Mutex rng");
19836
            return ret;
19837
        }
19838
        /* the above access to initGlobalRNG is racey -- recheck it now that we
19839
         * have the lock.
19840
         */
19841
        if (initGlobalRNG) {
19842
        #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
19843
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
19844
                 defined(HAVE_SELFTEST))
19845
            pid_t p;
19846
19847
            p = getpid();
19848
            if (p != currentRandPid) {
19849
                wc_UnLockMutex(&globalRNGMutex);
19850
                if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) {
19851
                    WOLFSSL_MSG("Issue with check pid and reseed");
19852
                    ret = WOLFSSL_FAILURE;
19853
                }
19854
19855
                /* reclaim lock after wolfSSL_RAND_poll */
19856
                if (wc_LockMutex(&globalRNGMutex) != 0) {
19857
                    WOLFSSL_MSG("Bad Lock Mutex rng");
19858
                    return ret;
19859
                }
19860
                currentRandPid = p;
19861
            }
19862
        #endif
19863
            rng = &globalRNG;
19864
            used_global = 1;
19865
        }
19866
        else {
19867
            wc_UnLockMutex(&globalRNGMutex);
19868
        }
19869
    }
19870
19871
    if (used_global == 0)
19872
#endif
19873
    {
19874
        WC_ALLOC_VAR_EX(tmpRNG, WC_RNG, 1, NULL, DYNAMIC_TYPE_RNG,
19875
            return ret);
19876
        if (wc_InitRng(tmpRNG) == 0) {
19877
            rng = tmpRNG;
19878
            initTmpRng = 1;
19879
        }
19880
    }
19881
    if (rng) {
19882
        /* handles size greater than RNG_MAX_BLOCK_LEN */
19883
        int blockCount = num / RNG_MAX_BLOCK_LEN;
19884
19885
        while (blockCount--) {
19886
            ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
19887
            if (ret != 0) {
19888
                WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
19889
                break;
19890
            }
19891
            num -= RNG_MAX_BLOCK_LEN;
19892
            buf += RNG_MAX_BLOCK_LEN;
19893
        }
19894
19895
        if (ret == 0 && num)
19896
            ret = wc_RNG_GenerateBlock(rng, buf, (word32)num);
19897
19898
        if (ret != 0)
19899
            WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
19900
        else
19901
            ret = WOLFSSL_SUCCESS;
19902
    }
19903
19904
#ifdef HAVE_GLOBAL_RNG
19905
    if (used_global == 1)
19906
        wc_UnLockMutex(&globalRNGMutex);
19907
#endif
19908
    if (initTmpRng)
19909
        wc_FreeRng(tmpRNG);
19910
    WC_FREE_VAR_EX(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
19911
19912
    return ret;
19913
}
19914
19915
19916
int wolfSSL_RAND_poll(void)
19917
{
19918
    byte  entropy[16];
19919
    int  ret = 0;
19920
    word32 entropy_sz = 16;
19921
19922
    WOLFSSL_ENTER("wolfSSL_RAND_poll");
19923
    if (initGlobalRNG == 0){
19924
        WOLFSSL_MSG("Global RNG no Init");
19925
        return  WOLFSSL_FAILURE;
19926
    }
19927
    ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
19928
    if (ret != 0) {
19929
        WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
19930
        ret = WOLFSSL_FAILURE;
19931
    }
19932
    else {
19933
#ifdef HAVE_HASHDRBG
19934
        if (wc_LockMutex(&globalRNGMutex) != 0) {
19935
            WOLFSSL_MSG("Bad Lock Mutex rng");
19936
            return ret;
19937
        }
19938
19939
        ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
19940
        if (ret != 0) {
19941
            WOLFSSL_MSG("Error reseeding DRBG");
19942
            ret = WOLFSSL_FAILURE;
19943
        }
19944
        else {
19945
            ret = WOLFSSL_SUCCESS;
19946
        }
19947
        wc_UnLockMutex(&globalRNGMutex);
19948
#elif defined(HAVE_INTEL_RDRAND)
19949
        WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without "
19950
                    "HAVE_HASHDRBG");
19951
        ret = WOLFSSL_SUCCESS;
19952
#else
19953
        WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set");
19954
        ret = WOLFSSL_FAILURE;
19955
#endif
19956
    }
19957
19958
    return ret;
19959
}
19960
19961
    /* If a valid struct is provided with function pointers, will override
19962
       RAND_seed, bytes, cleanup, add, pseudo_bytes and status.  If a NULL
19963
       pointer is passed in, it will cancel any previous function overrides.
19964
19965
       Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
19966
    int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
19967
    {
19968
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19969
        if (wolfSSL_RAND_InitMutex() == 0 &&
19970
                wc_LockMutex(&gRandMethodMutex) == 0) {
19971
            gRandMethods = methods;
19972
            wc_UnLockMutex(&gRandMethodMutex);
19973
            return WOLFSSL_SUCCESS;
19974
        }
19975
    #else
19976
        (void)methods;
19977
    #endif
19978
        return WOLFSSL_FAILURE;
19979
    }
19980
19981
    /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
19982
    int wolfSSL_RAND_status(void)
19983
    {
19984
        int ret = WOLFSSL_SUCCESS;
19985
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
19986
        if (wolfSSL_RAND_InitMutex() == 0 &&
19987
                wc_LockMutex(&gRandMethodMutex) == 0) {
19988
            if (gRandMethods && gRandMethods->status)
19989
                ret = gRandMethods->status();
19990
            wc_UnLockMutex(&gRandMethodMutex);
19991
        }
19992
        else {
19993
            ret = WOLFSSL_FAILURE;
19994
        }
19995
    #else
19996
        /* wolfCrypt provides enough seed internally, so return success */
19997
    #endif
19998
        return ret;
19999
    }
20000
20001
    void wolfSSL_RAND_add(const void* add, int len, double entropy)
20002
    {
20003
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
20004
        if (wolfSSL_RAND_InitMutex() == 0 &&
20005
                wc_LockMutex(&gRandMethodMutex) == 0) {
20006
            if (gRandMethods && gRandMethods->add) {
20007
                /* callback has return code, but RAND_add does not */
20008
                (void)gRandMethods->add(add, len, entropy);
20009
            }
20010
            wc_UnLockMutex(&gRandMethodMutex);
20011
        }
20012
    #else
20013
        /* wolfSSL seeds/adds internally, use explicit RNG if you want
20014
           to take control */
20015
        (void)add;
20016
        (void)len;
20017
        (void)entropy;
20018
    #endif
20019
    }
20020
20021
20022
#ifndef NO_WOLFSSL_STUB
20023
void wolfSSL_RAND_screen(void)
20024
{
20025
    WOLFSSL_STUB("RAND_screen");
20026
}
20027
#endif
20028
20029
int wolfSSL_RAND_load_file(const char* fname, long len)
20030
{
20031
    (void)fname;
20032
    /* wolfCrypt provides enough entropy internally or will report error */
20033
    if (len == -1)
20034
        return 1024;
20035
    else
20036
        return (int)len;
20037
}
20038
20039
#endif /* OPENSSL_EXTRA */
20040
20041
/*******************************************************************************
20042
 * END OF RAND API
20043
 ******************************************************************************/
20044
20045
/*******************************************************************************
20046
 * START OF EVP_CIPHER API
20047
 ******************************************************************************/
20048
20049
#ifdef OPENSSL_EXTRA
20050
20051
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
20052
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
20053
    {
20054
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
20055
20056
        if (ctx == NULL) {
20057
            WOLFSSL_MSG("Bad function argument");
20058
            return WOLFSSL_FATAL_ERROR;
20059
        }
20060
20061
        switch (ctx->cipherType) {
20062
#ifndef NO_AES
20063
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
20064
            case WC_AES_128_CBC_TYPE :
20065
            case WC_AES_192_CBC_TYPE :
20066
            case WC_AES_256_CBC_TYPE :
20067
                WOLFSSL_MSG("AES CBC");
20068
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
20069
                break;
20070
#endif
20071
#ifdef HAVE_AESGCM
20072
            case WC_AES_128_GCM_TYPE :
20073
            case WC_AES_192_GCM_TYPE :
20074
            case WC_AES_256_GCM_TYPE :
20075
                WOLFSSL_MSG("AES GCM");
20076
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
20077
                break;
20078
#endif /* HAVE_AESGCM */
20079
#ifdef HAVE_AESCCM
20080
            case WC_AES_128_CCM_TYPE :
20081
            case WC_AES_192_CCM_TYPE :
20082
            case WC_AES_256_CCM_TYPE :
20083
                WOLFSSL_MSG("AES CCM");
20084
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
20085
                break;
20086
#endif /* HAVE_AESCCM */
20087
#ifdef HAVE_AES_ECB
20088
            case WC_AES_128_ECB_TYPE :
20089
            case WC_AES_192_ECB_TYPE :
20090
            case WC_AES_256_ECB_TYPE :
20091
                WOLFSSL_MSG("AES ECB");
20092
                break;
20093
#endif
20094
#ifdef WOLFSSL_AES_COUNTER
20095
            case WC_AES_128_CTR_TYPE :
20096
            case WC_AES_192_CTR_TYPE :
20097
            case WC_AES_256_CTR_TYPE :
20098
                WOLFSSL_MSG("AES CTR");
20099
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
20100
                break;
20101
#endif /* WOLFSSL_AES_COUNTER */
20102
#ifdef WOLFSSL_AES_CFB
20103
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
20104
            case WC_AES_128_CFB1_TYPE:
20105
            case WC_AES_192_CFB1_TYPE:
20106
            case WC_AES_256_CFB1_TYPE:
20107
                WOLFSSL_MSG("AES CFB1");
20108
                break;
20109
            case WC_AES_128_CFB8_TYPE:
20110
            case WC_AES_192_CFB8_TYPE:
20111
            case WC_AES_256_CFB8_TYPE:
20112
                WOLFSSL_MSG("AES CFB8");
20113
                break;
20114
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
20115
            case WC_AES_128_CFB128_TYPE:
20116
            case WC_AES_192_CFB128_TYPE:
20117
            case WC_AES_256_CFB128_TYPE:
20118
                WOLFSSL_MSG("AES CFB128");
20119
                break;
20120
#endif /* WOLFSSL_AES_CFB */
20121
#if defined(WOLFSSL_AES_OFB)
20122
            case WC_AES_128_OFB_TYPE:
20123
            case WC_AES_192_OFB_TYPE:
20124
            case WC_AES_256_OFB_TYPE:
20125
                WOLFSSL_MSG("AES OFB");
20126
                break;
20127
#endif /* WOLFSSL_AES_OFB */
20128
#ifdef WOLFSSL_AES_XTS
20129
            case WC_AES_128_XTS_TYPE:
20130
            case WC_AES_256_XTS_TYPE:
20131
                WOLFSSL_MSG("AES XTS");
20132
                break;
20133
#endif /* WOLFSSL_AES_XTS */
20134
#endif /* NO_AES */
20135
20136
#ifdef HAVE_ARIA
20137
            case WC_ARIA_128_GCM_TYPE :
20138
            case WC_ARIA_192_GCM_TYPE :
20139
            case WC_ARIA_256_GCM_TYPE :
20140
                WOLFSSL_MSG("ARIA GCM");
20141
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
20142
                break;
20143
#endif /* HAVE_ARIA */
20144
20145
#ifndef NO_DES3
20146
            case WC_DES_CBC_TYPE :
20147
                WOLFSSL_MSG("DES CBC");
20148
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
20149
                break;
20150
20151
            case WC_DES_EDE3_CBC_TYPE :
20152
                WOLFSSL_MSG("DES EDE3 CBC");
20153
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
20154
                break;
20155
#endif
20156
#ifdef WOLFSSL_DES_ECB
20157
            case WC_DES_ECB_TYPE :
20158
                WOLFSSL_MSG("DES ECB");
20159
                break;
20160
            case WC_DES_EDE3_ECB_TYPE :
20161
                WOLFSSL_MSG("DES3 ECB");
20162
                break;
20163
#endif
20164
            case WC_ARC4_TYPE :
20165
                WOLFSSL_MSG("ARC4");
20166
                break;
20167
20168
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
20169
            case WC_CHACHA20_POLY1305_TYPE:
20170
                break;
20171
#endif
20172
20173
#ifdef HAVE_CHACHA
20174
            case WC_CHACHA20_TYPE:
20175
                break;
20176
#endif
20177
20178
#ifdef WOLFSSL_SM4_ECB
20179
            case WC_SM4_ECB_TYPE:
20180
                break;
20181
#endif
20182
#ifdef WOLFSSL_SM4_CBC
20183
            case WC_SM4_CBC_TYPE:
20184
                WOLFSSL_MSG("SM4 CBC");
20185
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
20186
                break;
20187
#endif
20188
#ifdef WOLFSSL_SM4_CTR
20189
            case WC_SM4_CTR_TYPE:
20190
                WOLFSSL_MSG("SM4 CTR");
20191
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
20192
                break;
20193
#endif
20194
#ifdef WOLFSSL_SM4_GCM
20195
            case WC_SM4_GCM_TYPE:
20196
                WOLFSSL_MSG("SM4 GCM");
20197
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
20198
                break;
20199
#endif
20200
#ifdef WOLFSSL_SM4_CCM
20201
            case WC_SM4_CCM_TYPE:
20202
                WOLFSSL_MSG("SM4 CCM");
20203
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
20204
                break;
20205
#endif
20206
20207
            case WC_NULL_CIPHER_TYPE :
20208
                WOLFSSL_MSG("NULL");
20209
                break;
20210
20211
            default: {
20212
                WOLFSSL_MSG("bad type");
20213
                return WOLFSSL_FATAL_ERROR;
20214
            }
20215
        }
20216
        return WOLFSSL_SUCCESS;
20217
    }
20218
20219
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
20220
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
20221
    {
20222
20223
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
20224
20225
        if (ctx == NULL) {
20226
            WOLFSSL_MSG("Bad function argument");
20227
            return WOLFSSL_FATAL_ERROR;
20228
        }
20229
20230
        switch (ctx->cipherType) {
20231
20232
#ifndef NO_AES
20233
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
20234
            case WC_AES_128_CBC_TYPE :
20235
            case WC_AES_192_CBC_TYPE :
20236
            case WC_AES_256_CBC_TYPE :
20237
                WOLFSSL_MSG("AES CBC");
20238
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
20239
                break;
20240
#endif
20241
#ifdef HAVE_AESGCM
20242
            case WC_AES_128_GCM_TYPE :
20243
            case WC_AES_192_GCM_TYPE :
20244
            case WC_AES_256_GCM_TYPE :
20245
                WOLFSSL_MSG("AES GCM");
20246
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
20247
                break;
20248
#endif
20249
#ifdef HAVE_AES_ECB
20250
            case WC_AES_128_ECB_TYPE :
20251
            case WC_AES_192_ECB_TYPE :
20252
            case WC_AES_256_ECB_TYPE :
20253
                WOLFSSL_MSG("AES ECB");
20254
                break;
20255
#endif
20256
#ifdef WOLFSSL_AES_COUNTER
20257
            case WC_AES_128_CTR_TYPE :
20258
            case WC_AES_192_CTR_TYPE :
20259
            case WC_AES_256_CTR_TYPE :
20260
                WOLFSSL_MSG("AES CTR");
20261
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
20262
                break;
20263
#endif
20264
20265
#endif /* NO_AES */
20266
20267
#ifdef HAVE_ARIA
20268
            case WC_ARIA_128_GCM_TYPE :
20269
            case WC_ARIA_192_GCM_TYPE :
20270
            case WC_ARIA_256_GCM_TYPE :
20271
                WOLFSSL_MSG("ARIA GCM");
20272
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
20273
                break;
20274
#endif /* HAVE_ARIA */
20275
20276
#ifndef NO_DES3
20277
            case WC_DES_CBC_TYPE :
20278
                WOLFSSL_MSG("DES CBC");
20279
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
20280
                break;
20281
20282
            case WC_DES_EDE3_CBC_TYPE :
20283
                WOLFSSL_MSG("DES EDE3 CBC");
20284
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
20285
                break;
20286
#endif
20287
#ifdef WOLFSSL_DES_ECB
20288
            case WC_DES_ECB_TYPE :
20289
                WOLFSSL_MSG("DES ECB");
20290
                break;
20291
            case WC_DES_EDE3_ECB_TYPE :
20292
                WOLFSSL_MSG("DES3 ECB");
20293
                break;
20294
#endif
20295
20296
            case WC_ARC4_TYPE :
20297
                WOLFSSL_MSG("ARC4");
20298
                break;
20299
20300
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
20301
            case WC_CHACHA20_POLY1305_TYPE:
20302
                break;
20303
#endif
20304
20305
#ifdef HAVE_CHACHA
20306
            case WC_CHACHA20_TYPE:
20307
                break;
20308
#endif
20309
20310
#ifdef WOLFSSL_SM4_ECB
20311
            case WC_SM4_ECB_TYPE:
20312
                break;
20313
#endif
20314
#ifdef WOLFSSL_SM4_CBC
20315
            case WC_SM4_CBC_TYPE:
20316
                WOLFSSL_MSG("SM4 CBC");
20317
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
20318
                break;
20319
#endif
20320
#ifdef WOLFSSL_SM4_CTR
20321
            case WC_SM4_CTR_TYPE:
20322
                WOLFSSL_MSG("SM4 CTR");
20323
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
20324
                break;
20325
#endif
20326
#ifdef WOLFSSL_SM4_GCM
20327
            case WC_SM4_GCM_TYPE:
20328
                WOLFSSL_MSG("SM4 GCM");
20329
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
20330
                break;
20331
#endif
20332
#ifdef WOLFSSL_SM4_CCM
20333
            case WC_SM4_CCM_TYPE:
20334
                WOLFSSL_MSG("SM4 CCM");
20335
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
20336
                break;
20337
#endif
20338
20339
            case WC_NULL_CIPHER_TYPE :
20340
                WOLFSSL_MSG("NULL");
20341
                break;
20342
20343
            default: {
20344
                WOLFSSL_MSG("bad type");
20345
                return WOLFSSL_FATAL_ERROR;
20346
            }
20347
        }
20348
        return WOLFSSL_SUCCESS;
20349
    }
20350
20351
#ifndef NO_DES3
20352
20353
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
20354
                            unsigned char* iv, int len)
20355
{
20356
    (void)len;
20357
20358
    WOLFSSL_MSG("wolfSSL_3des_iv");
20359
20360
    if (ctx == NULL || iv == NULL) {
20361
        WOLFSSL_MSG("Bad function argument");
20362
        return;
20363
    }
20364
20365
    if (doset)
20366
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
20367
    else
20368
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
20369
}
20370
20371
#endif /* NO_DES3 */
20372
20373
20374
#ifndef NO_AES
20375
20376
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
20377
                      unsigned char* iv, int len)
20378
{
20379
    (void)len;
20380
20381
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
20382
20383
    if (ctx == NULL || iv == NULL) {
20384
        WOLFSSL_MSG("Bad function argument");
20385
        return;
20386
    }
20387
20388
    if (doset)
20389
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
20390
    else
20391
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
20392
}
20393
20394
#endif /* NO_AES */
20395
20396
#endif /* OPENSSL_EXTRA */
20397
20398
/*******************************************************************************
20399
 * END OF EVP_CIPHER API
20400
 ******************************************************************************/
20401
20402
#ifndef NO_CERTS
20403
20404
#define WOLFSSL_X509_STORE_INCLUDED
20405
#include <src/x509_str.c>
20406
20407
#define WOLFSSL_SSL_P7P12_INCLUDED
20408
#include <src/ssl_p7p12.c>
20409
20410
#endif /* !NO_CERTS */
20411
20412
20413
/*******************************************************************************
20414
 * BEGIN OPENSSL FIPS DRBG APIs
20415
 ******************************************************************************/
20416
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
20417
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
20418
{
20419
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20420
    if (ctx != NULL) {
20421
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
20422
        ctx->type = type;
20423
        ctx->xflags = (int)flags;
20424
        ctx->status = DRBG_STATUS_UNINITIALISED;
20425
        ret = WOLFSSL_SUCCESS;
20426
    }
20427
    return ret;
20428
}
20429
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
20430
{
20431
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20432
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
20433
        NULL, DYNAMIC_TYPE_OPENSSL);
20434
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
20435
    if (ret == WOLFSSL_SUCCESS && type != 0) {
20436
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
20437
    }
20438
    if (ret != WOLFSSL_SUCCESS) {
20439
        WOLFSSL_ERROR(ret);
20440
        wolfSSL_FIPS_drbg_free(ctx);
20441
        ctx = NULL;
20442
    }
20443
    return ctx;
20444
}
20445
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
20446
    const unsigned char* pers, size_t perslen)
20447
{
20448
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20449
    if (ctx != NULL && ctx->rng == NULL) {
20450
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
20451
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
20452
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
20453
    #else
20454
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
20455
        if (ctx->rng != NULL) {
20456
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
20457
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
20458
        #else
20459
            ret = wc_InitRng(ctx->rng);
20460
            (void)pers;
20461
            (void)perslen;
20462
        #endif
20463
            if (ret != 0) {
20464
                WOLFSSL_ERROR(ret);
20465
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
20466
                ctx->rng = NULL;
20467
            }
20468
        }
20469
    #endif
20470
    }
20471
    if (ctx != NULL && ctx->rng != NULL) {
20472
        ctx->status = DRBG_STATUS_READY;
20473
        ret = WOLFSSL_SUCCESS;
20474
    }
20475
    return ret;
20476
}
20477
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
20478
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
20479
    size_t entropy_blocklen,
20480
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
20481
{
20482
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20483
    if (ctx != NULL) {
20484
        ctx->entropy_get = entropy_get;
20485
        ctx->entropy_clean = entropy_clean;
20486
        ctx->entropy_blocklen = entropy_blocklen;
20487
        ctx->none_get = none_get;
20488
        ctx->nonce_clean = nonce_clean;
20489
        ret = WOLFSSL_SUCCESS;
20490
    }
20491
    return ret;
20492
}
20493
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
20494
{
20495
    /* not implemented */
20496
    (void)buf;
20497
    (void)num;
20498
    (void)entropy;
20499
}
20500
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
20501
    size_t adinlen)
20502
{
20503
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20504
    if (ctx != NULL && ctx->rng != NULL) {
20505
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
20506
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
20507
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
20508
            ret = WOLFSSL_SUCCESS;
20509
        }
20510
    #else
20511
        ret = WOLFSSL_SUCCESS;
20512
        (void)adin;
20513
        (void)adinlen;
20514
    #endif
20515
    }
20516
    return ret;
20517
}
20518
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
20519
    size_t outlen, int prediction_resistance, const unsigned char* adin,
20520
    size_t adinlen)
20521
{
20522
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20523
    if (ctx != NULL && ctx->rng != NULL) {
20524
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
20525
        if (ret == 0) {
20526
            ret = WOLFSSL_SUCCESS;
20527
        }
20528
    }
20529
    (void)prediction_resistance;
20530
    (void)adin;
20531
    (void)adinlen;
20532
    return ret;
20533
}
20534
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
20535
{
20536
    if (ctx != NULL && ctx->rng != NULL) {
20537
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
20538
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
20539
        wc_rng_free(ctx->rng);
20540
    #else
20541
        wc_FreeRng(ctx->rng);
20542
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
20543
    #endif
20544
        ctx->rng = NULL;
20545
        ctx->status = DRBG_STATUS_UNINITIALISED;
20546
    }
20547
    return WOLFSSL_SUCCESS;
20548
}
20549
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
20550
{
20551
    if (ctx != NULL) {
20552
        /* As safety check if free'ing the default drbg, then mark global NULL.
20553
         * Technically the user should not call free on the default drbg. */
20554
        if (ctx == gDrbgDefCtx) {
20555
            gDrbgDefCtx = NULL;
20556
        }
20557
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
20558
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
20559
    }
20560
}
20561
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
20562
{
20563
    if (gDrbgDefCtx == NULL) {
20564
        gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
20565
    }
20566
    return gDrbgDefCtx;
20567
}
20568
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
20569
{
20570
    /* not implemented */
20571
    (void)buf;
20572
    (void)pctr;
20573
}
20574
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
20575
{
20576
    if (ctx != NULL) {
20577
        return ctx->app_data;
20578
    }
20579
    return NULL;
20580
}
20581
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
20582
{
20583
    if (ctx != NULL) {
20584
        ctx->app_data = app_data;
20585
    }
20586
}
20587
#endif
20588
/*******************************************************************************
20589
 * END OF OPENSSL FIPS DRBG APIs
20590
 ******************************************************************************/
20591
20592
20593
#endif /* !WOLFCRYPT_ONLY */