Coverage Report

Created: 2025-12-31 07:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-fastmath/src/ssl.c
Line
Count
Source
1
/* ssl.c
2
 *
3
 * Copyright (C) 2006-2025 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/coding.h>
35
#include <wolfssl/wolfcrypt/kdf.h>
36
#ifdef NO_INLINE
37
    #include <wolfssl/wolfcrypt/misc.h>
38
#else
39
    #define WOLFSSL_MISC_INCLUDED
40
    #include <wolfcrypt/src/misc.c>
41
#endif
42
43
#ifdef HAVE_ERRNO_H
44
    #include <errno.h>
45
#endif
46
47
48
#if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
49
    #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
50
                && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
51
                && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
52
        #error "No cipher suites defined because DH disabled, ECC disabled, " \
53
               "and no static suites defined. Please see top of README"
54
    #endif
55
    #ifdef WOLFSSL_CERT_GEN
56
        /* need access to Cert struct for creating certificate */
57
        #include <wolfssl/wolfcrypt/asn_public.h>
58
    #endif
59
#endif
60
61
#if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA)     \
62
    || defined(OPENSSL_EXTRA_X509_SMALL)                    \
63
    || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
64
    #include <wolfssl/openssl/evp.h>
65
    /* openssl headers end, wolfssl internal headers next */
66
#endif
67
68
#include <wolfssl/wolfcrypt/wc_encrypt.h>
69
70
#ifndef NO_RSA
71
    #include <wolfssl/wolfcrypt/rsa.h>
72
#endif
73
74
#ifdef OPENSSL_EXTRA
75
    /* openssl headers begin */
76
    #include <wolfssl/openssl/ssl.h>
77
    #include <wolfssl/openssl/aes.h>
78
#ifndef WOLFCRYPT_ONLY
79
    #include <wolfssl/openssl/hmac.h>
80
    #include <wolfssl/openssl/cmac.h>
81
#endif
82
    #include <wolfssl/openssl/crypto.h>
83
    #include <wolfssl/openssl/des.h>
84
    #include <wolfssl/openssl/bn.h>
85
    #include <wolfssl/openssl/buffer.h>
86
    #include <wolfssl/openssl/dh.h>
87
    #include <wolfssl/openssl/rsa.h>
88
    #include <wolfssl/openssl/fips_rand.h>
89
    #include <wolfssl/openssl/pem.h>
90
    #include <wolfssl/openssl/ec.h>
91
    #include <wolfssl/openssl/ec25519.h>
92
    #include <wolfssl/openssl/ed25519.h>
93
    #include <wolfssl/openssl/ec448.h>
94
    #include <wolfssl/openssl/ed448.h>
95
    #include <wolfssl/openssl/ecdsa.h>
96
    #include <wolfssl/openssl/ecdh.h>
97
    #include <wolfssl/openssl/err.h>
98
    #include <wolfssl/openssl/modes.h>
99
    #include <wolfssl/openssl/opensslv.h>
100
    #include <wolfssl/openssl/rc4.h>
101
    #include <wolfssl/openssl/stack.h>
102
    #include <wolfssl/openssl/x509_vfy.h>
103
    /* openssl headers end, wolfssl internal headers next */
104
    #include <wolfssl/wolfcrypt/hmac.h>
105
    #include <wolfssl/wolfcrypt/random.h>
106
    #include <wolfssl/wolfcrypt/des3.h>
107
    #include <wolfssl/wolfcrypt/ecc.h>
108
    #include <wolfssl/wolfcrypt/md4.h>
109
    #include <wolfssl/wolfcrypt/md5.h>
110
    #include <wolfssl/wolfcrypt/arc4.h>
111
    #include <wolfssl/wolfcrypt/curve25519.h>
112
    #include <wolfssl/wolfcrypt/ed25519.h>
113
    #include <wolfssl/wolfcrypt/curve448.h>
114
    #if defined(HAVE_FALCON)
115
        #include <wolfssl/wolfcrypt/falcon.h>
116
    #endif /* HAVE_FALCON */
117
    #if defined(HAVE_DILITHIUM)
118
        #include <wolfssl/wolfcrypt/dilithium.h>
119
    #endif /* HAVE_DILITHIUM */
120
    #if defined(HAVE_SPHINCS)
121
        #include <wolfssl/wolfcrypt/sphincs.h>
122
    #endif /* HAVE_SPHINCS */
123
    #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
124
        #ifdef HAVE_OCSP
125
            #include <wolfssl/openssl/ocsp.h>
126
        #endif
127
        #include <wolfssl/openssl/lhash.h>
128
        #include <wolfssl/openssl/txt_db.h>
129
    #endif /* WITH_STUNNEL */
130
    #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
131
        #include <wolfssl/wolfcrypt/sha512.h>
132
    #endif
133
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
134
        && !defined(WC_NO_RNG)
135
        #include <wolfssl/wolfcrypt/srp.h>
136
    #endif
137
#endif
138
139
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
140
    #include <wolfssl/openssl/x509v3.h>
141
    int wolfssl_bn_get_value(WOLFSSL_BIGNUM* bn, mp_int* mpi);
142
    int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi);
143
#endif
144
145
#if defined(WOLFSSL_QT)
146
    #include <wolfssl/wolfcrypt/sha.h>
147
#endif
148
149
#ifdef NO_ASN
150
    #include <wolfssl/wolfcrypt/dh.h>
151
#endif
152
#endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
153
154
/*
155
 * OPENSSL_COMPATIBLE_DEFAULTS:
156
 *     Enable default behaviour that is compatible with OpenSSL. For example
157
 *     SSL_CTX by default doesn't verify the loaded certs. Enabling this
158
 *     should make porting to new projects easier.
159
 * WOLFSSL_CHECK_ALERT_ON_ERR:
160
 *     Check for alerts during the handshake in the event of an error.
161
 * NO_SESSION_CACHE_REF:
162
 *     wolfSSL_get_session on a client will return a reference to the internal
163
 *     ClientCache by default for backwards compatibility. This define will
164
 *     make wolfSSL_get_session return a reference to ssl->session. The returned
165
 *     pointer will be freed with the related WOLFSSL object.
166
 * SESSION_CACHE_DYNAMIC_MEM:
167
 *     Dynamically allocate sessions for the session cache from the heap, as
168
 *     opposed to the default which allocates from the stack.  Allocates
169
 *     memory only when a session is added to the cache, frees memory after the
170
 *     session is no longer being used.  Recommended for memory-constrained
171
 *     systems.
172
 * WOLFSSL_SYS_CA_CERTS
173
 *     Enables ability to load system CA certs from the OS via
174
 *     wolfSSL_CTX_load_system_CA_certs.
175
 */
176
177
#define WOLFSSL_SSL_MISC_INCLUDED
178
#include "src/ssl_misc.c"
179
180
#define WOLFSSL_EVP_INCLUDED
181
#include "wolfcrypt/src/evp.c"
182
183
/* Crypto code uses EVP APIs. */
184
#define WOLFSSL_SSL_CRYPTO_INCLUDED
185
#include "src/ssl_crypto.c"
186
187
#ifndef WOLFCRYPT_ONLY
188
#define WOLFSSL_SSL_CERTMAN_INCLUDED
189
#include "src/ssl_certman.c"
190
191
#define WOLFSSL_SSL_SESS_INCLUDED
192
#include "src/ssl_sess.c"
193
#endif
194
195
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
196
    !defined(WOLFCRYPT_ONLY)
197
/* Convert shortname to NID.
198
 *
199
 * For OpenSSL compatibility.
200
 *
201
 * @param [in] sn  Short name of OID.
202
 * @return  NID corresponding to shortname on success.
203
 * @return  WC_NID_undef when not recognized.
204
 */
205
int wc_OBJ_sn2nid(const char *sn)
206
{
207
    const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
208
    size_t i;
209
    WOLFSSL_ENTER("wc_OBJ_sn2nid");
210
    for (i = 0; i < wolfssl_object_info_sz; i++, obj_info++) {
211
        if (XSTRCMP(sn, obj_info->sName) == 0)
212
            return obj_info->nid;
213
    }
214
    WOLFSSL_MSG("short name not found in table");
215
    return WC_NID_undef;
216
}
217
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
218
219
#ifndef WOLFCRYPT_ONLY
220
221
222
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
223
/* The system wide crypto-policy. Configured by wolfSSL_crypto_policy_enable.
224
 * */
225
static struct SystemCryptoPolicy crypto_policy;
226
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
227
228
#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \
229
    (defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && !defined(NO_DSA))
230
231
#define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
232
static WC_RNG globalRNG;
233
static volatile int initGlobalRNG = 0;
234
235
#if defined(OPENSSL_EXTRA) || !defined(WOLFSSL_MUTEX_INITIALIZER)
236
static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex
237
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex);
238
#endif
239
#ifndef WOLFSSL_MUTEX_INITIALIZER
240
static int globalRNGMutex_valid = 0;
241
#endif
242
243
#if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
244
static WOLFSSL_DRBG_CTX* gDrbgDefCtx = NULL;
245
#endif
246
247
WC_RNG* wolfssl_get_global_rng(void)
248
442
{
249
442
    WC_RNG* ret = NULL;
250
251
442
    if (initGlobalRNG == 0)
252
423
        WOLFSSL_MSG("Global RNG no Init");
253
19
    else
254
19
        ret = &globalRNG;
255
256
442
    return ret;
257
442
}
258
259
/* Make a global RNG and return.
260
 *
261
 * @return  Global RNG on success.
262
 * @return  NULL on error.
263
 */
264
WC_RNG* wolfssl_make_global_rng(void)
265
0
{
266
0
    WC_RNG* ret;
267
268
0
#ifdef HAVE_GLOBAL_RNG
269
    /* Get the global random number generator instead. */
270
0
    ret = wolfssl_get_global_rng();
271
#ifdef OPENSSL_EXTRA
272
    if (ret == NULL) {
273
        /* Create a global random if possible. */
274
        (void)wolfSSL_RAND_Init();
275
        ret = wolfssl_get_global_rng();
276
    }
277
#endif
278
#else
279
    WOLFSSL_ERROR_MSG("Bad RNG Init");
280
    ret = NULL;
281
#endif
282
283
0
    return ret;
284
0
}
285
286
/* Too many defines to check explicitly - prototype it and always include
287
 * for RSA, DH, ECC and DSA for BN. */
288
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local);
289
290
/* Make a random number generator or get global if possible.
291
 *
292
 * Global may not be available and NULL will be returned.
293
 *
294
 * @param [in, out] rng    Local random number generator.
295
 * @param [out]     local  Local random number generator returned.
296
 * @return  NULL on failure.
297
 * @return  A random number generator object.
298
 */
299
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local)
300
604
{
301
604
    WC_RNG* ret = NULL;
302
604
#ifdef WOLFSSL_SMALL_STACK
303
604
    int freeRng = 0;
304
305
    /* Allocate RNG object . */
306
604
    if (rng == NULL) {
307
604
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
308
604
        freeRng = 1;
309
604
    }
310
604
#endif
311
312
604
    if (rng != NULL) {
313
604
        if (wc_InitRng(rng) == 0) {
314
604
            ret = rng;
315
604
            *local = 1;
316
604
        }
317
0
        else {
318
0
            WOLFSSL_MSG("Bad RNG Init");
319
0
#ifdef WOLFSSL_SMALL_STACK
320
0
            if (freeRng) {
321
0
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
322
0
                rng = NULL;
323
0
            }
324
0
#endif
325
0
        }
326
604
    }
327
604
    if (ret == NULL) {
328
0
#ifdef HAVE_GLOBAL_RNG
329
0
        WOLFSSL_MSG("trying global RNG");
330
0
#endif
331
0
        ret = wolfssl_make_global_rng();
332
0
    }
333
334
604
    return ret;
335
604
}
336
#endif
337
338
#ifdef OPENSSL_EXTRA
339
    /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
340
     *                OPENSSL_EXTRA where RAND callbacks are not used */
341
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
342
        static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
343
        static wolfSSL_Mutex gRandMethodMutex
344
            WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex);
345
        #ifndef WOLFSSL_MUTEX_INITIALIZER
346
        static int gRandMethodsInit = 0;
347
        #endif
348
    #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
349
#endif /* OPENSSL_EXTRA */
350
351
#define WOLFSSL_SSL_BN_INCLUDED
352
#include "src/ssl_bn.c"
353
354
#ifndef OPENSSL_EXTRA_NO_ASN1
355
#define WOLFSSL_SSL_ASN1_INCLUDED
356
#include "src/ssl_asn1.c"
357
#endif /* OPENSSL_EXTRA_NO_ASN1 */
358
359
#define WOLFSSL_PK_INCLUDED
360
#include "src/pk.c"
361
362
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
363
/* copies over data of "in" to "out" */
364
static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out)
365
{
366
    if (in == NULL || out == NULL)
367
        return;
368
369
    *out = *in;
370
}
371
372
373
#if defined(OPENSSL_ALL)
374
static WOLFSSL_X509_OBJECT* wolfSSL_X509_OBJECT_dup(WOLFSSL_X509_OBJECT* obj)
375
{
376
    WOLFSSL_X509_OBJECT* ret = NULL;
377
    if (obj) {
378
        ret = wolfSSL_X509_OBJECT_new();
379
        if (ret) {
380
            ret->type = obj->type;
381
            switch (ret->type) {
382
                case WOLFSSL_X509_LU_NONE:
383
                    break;
384
                case WOLFSSL_X509_LU_X509:
385
                    ret->data.x509 = wolfSSL_X509_dup(obj->data.x509);
386
                    break;
387
                case WOLFSSL_X509_LU_CRL:
388
            #if defined(HAVE_CRL)
389
                    ret->data.crl = wolfSSL_X509_CRL_dup(obj->data.crl);
390
            #endif
391
                    break;
392
            }
393
        }
394
    }
395
    return ret;
396
}
397
#endif /* OPENSSL_ALL */
398
399
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
400
401
#define WOLFSSL_SSL_SK_INCLUDED
402
#include "src/ssl_sk.c"
403
404
405
#include <wolfssl/wolfcrypt/hpke.h>
406
407
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
408
/* create the hpke key and ech config to send to clients */
409
int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName,
410
    word16 kemId, word16 kdfId, word16 aeadId)
411
{
412
    int ret = 0;
413
    word16 encLen = DHKEM_X25519_ENC_LEN;
414
    WOLFSSL_EchConfig* newConfig;
415
    WOLFSSL_EchConfig* parentConfig;
416
#ifdef WOLFSSL_SMALL_STACK
417
    Hpke* hpke = NULL;
418
    WC_RNG* rng;
419
#else
420
    Hpke hpke[1];
421
    WC_RNG rng[1];
422
#endif
423
424
    if (ctx == NULL || publicName == NULL)
425
        return BAD_FUNC_ARG;
426
427
    WC_ALLOC_VAR_EX(rng, WC_RNG, 1, ctx->heap, DYNAMIC_TYPE_RNG,
428
        return MEMORY_E);
429
    ret = wc_InitRng(rng);
430
    if (ret != 0) {
431
        WC_FREE_VAR_EX(rng, ctx->heap, DYNAMIC_TYPE_RNG);
432
        return ret;
433
    }
434
435
    newConfig = (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig),
436
        ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
437
    if (newConfig == NULL)
438
        ret = MEMORY_E;
439
    else
440
        XMEMSET(newConfig, 0, sizeof(WOLFSSL_EchConfig));
441
442
    /* set random config id */
443
    if (ret == 0)
444
        ret = wc_RNG_GenerateByte(rng, &newConfig->configId);
445
446
    /* if 0 is selected for algorithms use default, may change with draft */
447
    if (kemId == 0)
448
        kemId = DHKEM_X25519_HKDF_SHA256;
449
450
    if (kdfId == 0)
451
        kdfId = HKDF_SHA256;
452
453
    if (aeadId == 0)
454
        aeadId = HPKE_AES_128_GCM;
455
456
    if (ret == 0) {
457
        /* set the kem id */
458
        newConfig->kemId = kemId;
459
460
        /* set the cipher suite, only 1 for now */
461
        newConfig->numCipherSuites = 1;
462
        newConfig->cipherSuites =
463
            (EchCipherSuite*)XMALLOC(sizeof(EchCipherSuite), ctx->heap,
464
            DYNAMIC_TYPE_TMP_BUFFER);
465
466
        if (newConfig->cipherSuites == NULL) {
467
            ret = MEMORY_E;
468
        }
469
        else {
470
            newConfig->cipherSuites[0].kdfId = kdfId;
471
            newConfig->cipherSuites[0].aeadId = aeadId;
472
        }
473
    }
474
475
#ifdef WOLFSSL_SMALL_STACK
476
    if (ret == 0) {
477
        hpke = (Hpke*)XMALLOC(sizeof(Hpke), ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
478
        if (hpke == NULL)
479
            ret = MEMORY_E;
480
    }
481
#endif
482
483
    if (ret == 0)
484
        ret = wc_HpkeInit(hpke, kemId, kdfId, aeadId, ctx->heap);
485
486
    /* generate the receiver private key */
487
    if (ret == 0)
488
        ret = wc_HpkeGenerateKeyPair(hpke, &newConfig->receiverPrivkey, rng);
489
490
    /* done with RNG */
491
    wc_FreeRng(rng);
492
493
    /* serialize the receiver key */
494
    if (ret == 0)
495
        ret = wc_HpkeSerializePublicKey(hpke, newConfig->receiverPrivkey,
496
            newConfig->receiverPubkey, &encLen);
497
498
    if (ret == 0) {
499
        newConfig->publicName = (char*)XMALLOC(XSTRLEN(publicName) + 1,
500
            ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
501
        if (newConfig->publicName == NULL) {
502
            ret = MEMORY_E;
503
        }
504
        else {
505
            XMEMCPY(newConfig->publicName, publicName,
506
                XSTRLEN(publicName) + 1);
507
        }
508
    }
509
510
    if (ret != 0) {
511
        if (newConfig) {
512
            XFREE(newConfig->cipherSuites, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
513
            XFREE(newConfig->publicName, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
514
            XFREE(newConfig, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
515
        }
516
    }
517
    else {
518
        parentConfig = ctx->echConfigs;
519
520
        if (parentConfig == NULL) {
521
            ctx->echConfigs = newConfig;
522
        }
523
        else {
524
            while (parentConfig->next != NULL) {
525
                parentConfig = parentConfig->next;
526
            }
527
528
            parentConfig->next = newConfig;
529
        }
530
    }
531
532
    if (ret == 0)
533
        ret = WOLFSSL_SUCCESS;
534
535
    WC_FREE_VAR_EX(hpke, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
536
    WC_FREE_VAR_EX(rng, ctx->heap, DYNAMIC_TYPE_RNG);
537
538
    return ret;
539
}
540
541
int wolfSSL_CTX_SetEchConfigsBase64(WOLFSSL_CTX* ctx, const char* echConfigs64,
542
    word32 echConfigs64Len)
543
{
544
    int ret = 0;
545
    word32 decodedLen = echConfigs64Len * 3 / 4 + 1;
546
    byte* decodedConfigs;
547
548
    if (ctx == NULL || echConfigs64 == NULL || echConfigs64Len == 0)
549
        return BAD_FUNC_ARG;
550
551
    decodedConfigs = (byte*)XMALLOC(decodedLen, ctx->heap,
552
        DYNAMIC_TYPE_TMP_BUFFER);
553
554
    if (decodedConfigs == NULL)
555
        return MEMORY_E;
556
557
    decodedConfigs[decodedLen - 1] = 0;
558
559
    /* decode the echConfigs */
560
    ret = Base64_Decode((const byte*)echConfigs64, echConfigs64Len,
561
        decodedConfigs, &decodedLen);
562
563
    if (ret != 0) {
564
        XFREE(decodedConfigs, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
565
        return ret;
566
    }
567
568
    ret = wolfSSL_CTX_SetEchConfigs(ctx, decodedConfigs, decodedLen);
569
570
    XFREE(decodedConfigs, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER);
571
572
    return ret;
573
}
574
575
int wolfSSL_CTX_SetEchConfigs(WOLFSSL_CTX* ctx, const byte* echConfigs,
576
    word32 echConfigsLen)
577
{
578
    int ret;
579
580
    if (ctx == NULL || echConfigs == NULL || echConfigsLen == 0)
581
        return BAD_FUNC_ARG;
582
583
    FreeEchConfigs(ctx->echConfigs, ctx->heap);
584
    ctx->echConfigs = NULL;
585
    ret = SetEchConfigsEx(&ctx->echConfigs, ctx->heap, echConfigs,
586
        echConfigsLen);
587
588
    if (ret == 0)
589
        return WOLFSSL_SUCCESS;
590
591
    return ret;
592
}
593
594
/* get the ech configs that the server context is using */
595
int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output,
596
    word32* outputLen) {
597
    if (ctx == NULL || outputLen == NULL)
598
        return BAD_FUNC_ARG;
599
600
    /* if we don't have ech configs */
601
    if (ctx->echConfigs == NULL)
602
        return WOLFSSL_FATAL_ERROR;
603
604
    return GetEchConfigsEx(ctx->echConfigs, output, outputLen);
605
}
606
607
void wolfSSL_CTX_SetEchEnable(WOLFSSL_CTX* ctx, byte enable)
608
{
609
    if (ctx != NULL) {
610
        ctx->disableECH = !enable;
611
        if (ctx->disableECH) {
612
            TLSX_Remove(&ctx->extensions, TLSX_ECH, ctx->heap);
613
            FreeEchConfigs(ctx->echConfigs, ctx->heap);
614
            ctx->echConfigs = NULL;
615
        }
616
    }
617
}
618
619
/* set the ech config from base64 for our client ssl object, base64 is the
620
 * format ech configs are sent using dns records */
621
int wolfSSL_SetEchConfigsBase64(WOLFSSL* ssl, char* echConfigs64,
622
    word32 echConfigs64Len)
623
{
624
    int ret = 0;
625
    word32 decodedLen = echConfigs64Len * 3 / 4 + 1;
626
    byte* decodedConfigs;
627
628
    if (ssl == NULL || echConfigs64 == NULL || echConfigs64Len == 0)
629
        return BAD_FUNC_ARG;
630
631
    /* already have ech configs */
632
    if (ssl->options.useEch == 1) {
633
        return WOLFSSL_FATAL_ERROR;
634
    }
635
636
    decodedConfigs = (byte*)XMALLOC(decodedLen, ssl->heap,
637
        DYNAMIC_TYPE_TMP_BUFFER);
638
639
    if (decodedConfigs == NULL)
640
        return MEMORY_E;
641
642
    decodedConfigs[decodedLen - 1] = 0;
643
644
    /* decode the echConfigs */
645
    ret = Base64_Decode((byte*)echConfigs64, echConfigs64Len,
646
      decodedConfigs, &decodedLen);
647
648
    if (ret != 0) {
649
        XFREE(decodedConfigs, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
650
        return ret;
651
    }
652
653
    ret = wolfSSL_SetEchConfigs(ssl, decodedConfigs, decodedLen);
654
655
    XFREE(decodedConfigs, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
656
657
    return ret;
658
}
659
660
/* set the ech config from a raw buffer, this is the format ech configs are
661
 * sent using retry_configs from the ech server */
662
int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs,
663
    word32 echConfigsLen)
664
{
665
    int ret;
666
667
    if (ssl == NULL || echConfigs == NULL || echConfigsLen == 0)
668
        return BAD_FUNC_ARG;
669
670
    /* already have ech configs */
671
    if (ssl->options.useEch == 1) {
672
        return WOLFSSL_FATAL_ERROR;
673
    }
674
675
    ret = SetEchConfigsEx(&ssl->echConfigs, ssl->heap, echConfigs,
676
        echConfigsLen);
677
678
    /* if we found valid configs */
679
    if (ret == 0) {
680
        ssl->options.useEch = 1;
681
        return WOLFSSL_SUCCESS;
682
    }
683
684
    return ret;
685
}
686
687
/* get the raw ech config from our struct */
688
int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, word32* outputLen)
689
{
690
    int i;
691
    word16 totalLen = 0;
692
693
    if (config == NULL || (output == NULL && outputLen == NULL))
694
        return BAD_FUNC_ARG;
695
696
    /* 2 for version */
697
    totalLen += 2;
698
    /* 2 for length */
699
    totalLen += 2;
700
    /* 1 for configId */
701
    totalLen += 1;
702
    /* 2 for kemId */
703
    totalLen += 2;
704
    /* 2 for hpke_len */
705
    totalLen += 2;
706
707
    /* hpke_pub_key */
708
    switch (config->kemId) {
709
        case DHKEM_P256_HKDF_SHA256:
710
            totalLen += DHKEM_P256_ENC_LEN;
711
            break;
712
        case DHKEM_P384_HKDF_SHA384:
713
            totalLen += DHKEM_P384_ENC_LEN;
714
            break;
715
        case DHKEM_P521_HKDF_SHA512:
716
            totalLen += DHKEM_P521_ENC_LEN;
717
            break;
718
        case DHKEM_X25519_HKDF_SHA256:
719
            totalLen += DHKEM_X25519_ENC_LEN;
720
            break;
721
        case DHKEM_X448_HKDF_SHA512:
722
            totalLen += DHKEM_X448_ENC_LEN;
723
            break;
724
    }
725
726
    /* cipherSuitesLen */
727
    totalLen += 2;
728
    /* cipherSuites */
729
    totalLen += config->numCipherSuites * 4;
730
    /* public name len */
731
    totalLen += 2;
732
733
    /* public name */
734
    totalLen += XSTRLEN(config->publicName);
735
    /* trailing zeros */
736
    totalLen += 2;
737
738
    if (output == NULL) {
739
        *outputLen = totalLen;
740
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
741
    }
742
743
    if (totalLen > *outputLen) {
744
        *outputLen = totalLen;
745
        return INPUT_SIZE_E;
746
    }
747
748
    /* version */
749
    c16toa(TLSX_ECH, output);
750
    output += 2;
751
752
    /* length - 4 for version and length itself */
753
    c16toa(totalLen - 4, output);
754
    output += 2;
755
756
    /* configId */
757
    *output = config->configId;
758
    output++;
759
    /* kemId */
760
    c16toa(config->kemId, output);
761
    output += 2;
762
763
    /* length and key itself */
764
    switch (config->kemId) {
765
        case DHKEM_P256_HKDF_SHA256:
766
            c16toa(DHKEM_P256_ENC_LEN, output);
767
            output += 2;
768
            XMEMCPY(output, config->receiverPubkey, DHKEM_P256_ENC_LEN);
769
            output += DHKEM_P256_ENC_LEN;
770
            break;
771
        case DHKEM_P384_HKDF_SHA384:
772
            c16toa(DHKEM_P384_ENC_LEN, output);
773
            output += 2;
774
            XMEMCPY(output, config->receiverPubkey, DHKEM_P384_ENC_LEN);
775
            output += DHKEM_P384_ENC_LEN;
776
            break;
777
        case DHKEM_P521_HKDF_SHA512:
778
            c16toa(DHKEM_P521_ENC_LEN, output);
779
            output += 2;
780
            XMEMCPY(output, config->receiverPubkey, DHKEM_P521_ENC_LEN);
781
            output += DHKEM_P521_ENC_LEN;
782
            break;
783
        case DHKEM_X25519_HKDF_SHA256:
784
            c16toa(DHKEM_X25519_ENC_LEN, output);
785
            output += 2;
786
            XMEMCPY(output, config->receiverPubkey, DHKEM_X25519_ENC_LEN);
787
            output += DHKEM_X25519_ENC_LEN;
788
            break;
789
        case DHKEM_X448_HKDF_SHA512:
790
            c16toa(DHKEM_X448_ENC_LEN, output);
791
            output += 2;
792
            XMEMCPY(output, config->receiverPubkey, DHKEM_X448_ENC_LEN);
793
            output += DHKEM_X448_ENC_LEN;
794
            break;
795
    }
796
797
    /* cipherSuites len */
798
    c16toa(config->numCipherSuites * 4, output);
799
    output += 2;
800
801
    /* cipherSuites */
802
    for (i = 0; i < config->numCipherSuites; i++) {
803
        c16toa(config->cipherSuites[i].kdfId, output);
804
        output += 2;
805
        c16toa(config->cipherSuites[i].aeadId, output);
806
        output += 2;
807
    }
808
809
    /* set maximum name length to 0 */
810
    *output = 0;
811
    output++;
812
813
    /* publicName len */
814
    *output = XSTRLEN(config->publicName);
815
    output++;
816
817
    /* publicName */
818
    XMEMCPY(output, config->publicName,
819
        XSTRLEN(config->publicName));
820
    output += XSTRLEN(config->publicName);
821
822
    /* terminating zeros */
823
    c16toa(0, output);
824
    /* output += 2; */
825
826
    *outputLen = totalLen;
827
828
    return 0;
829
}
830
831
/* wrapper function to get ech configs from application code */
832
int wolfSSL_GetEchConfigs(WOLFSSL* ssl, byte* output, word32* outputLen)
833
{
834
    if (ssl == NULL || outputLen == NULL)
835
        return BAD_FUNC_ARG;
836
837
    /* if we don't have ech configs */
838
    if (ssl->options.useEch != 1) {
839
        return WOLFSSL_FATAL_ERROR;
840
    }
841
842
    return GetEchConfigsEx(ssl->echConfigs, output, outputLen);
843
}
844
845
void wolfSSL_SetEchEnable(WOLFSSL* ssl, byte enable)
846
{
847
    if (ssl != NULL) {
848
        ssl->options.disableECH = !enable;
849
        if (ssl->options.disableECH) {
850
            TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap);
851
            FreeEchConfigs(ssl->echConfigs, ssl->heap);
852
            ssl->echConfigs = NULL;
853
        }
854
    }
855
}
856
857
int SetEchConfigsEx(WOLFSSL_EchConfig** outputConfigs, void* heap,
858
    const byte* echConfigs, word32 echConfigsLen)
859
{
860
    int ret = 0;
861
    int i;
862
    int j;
863
    word16 totalLength;
864
    word16 version;
865
    word16 length;
866
    word16 hpkePubkeyLen;
867
    word16 cipherSuitesLen;
868
    word16 publicNameLen;
869
    WOLFSSL_EchConfig* configList = NULL;
870
    WOLFSSL_EchConfig* workingConfig = NULL;
871
    WOLFSSL_EchConfig* lastConfig = NULL;
872
    byte* echConfig = NULL;
873
874
    if (outputConfigs == NULL || echConfigs == NULL || echConfigsLen == 0)
875
        return BAD_FUNC_ARG;
876
877
    /* check that the total length is well formed */
878
    ato16(echConfigs, &totalLength);
879
880
    if (totalLength != echConfigsLen - 2) {
881
        return WOLFSSL_FATAL_ERROR;
882
    }
883
884
    /* skip the total length uint16_t */
885
    i = 2;
886
887
    do {
888
        echConfig = (byte*)echConfigs + i;
889
        ato16(echConfig, &version);
890
        ato16(echConfig + 2, &length);
891
892
        /* if the version does not match */
893
        if (version != TLSX_ECH) {
894
            /* we hit the end of the configs */
895
            if ( (word32)i + 2 >= echConfigsLen ) {
896
                break;
897
            }
898
899
            /* skip this config, +4 for version and length */
900
            i += length + 4;
901
            continue;
902
        }
903
904
        /* check if the length will overrun the buffer */
905
        if ((word32)i + length + 4 > echConfigsLen) {
906
            break;
907
        }
908
909
        if (workingConfig == NULL) {
910
            workingConfig =
911
                (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), heap,
912
                DYNAMIC_TYPE_TMP_BUFFER);
913
            configList = workingConfig;
914
            if (workingConfig != NULL) {
915
                workingConfig->next = NULL;
916
            }
917
        }
918
        else {
919
            lastConfig = workingConfig;
920
            workingConfig->next =
921
                (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig),
922
                heap, DYNAMIC_TYPE_TMP_BUFFER);
923
            workingConfig = workingConfig->next;
924
        }
925
926
        if (workingConfig == NULL) {
927
            ret = MEMORY_E;
928
            break;
929
        }
930
931
        XMEMSET(workingConfig, 0, sizeof(WOLFSSL_EchConfig));
932
933
        /* rawLen */
934
        workingConfig->rawLen = length + 4;
935
936
        /* raw body */
937
        workingConfig->raw = (byte*)XMALLOC(workingConfig->rawLen,
938
            heap, DYNAMIC_TYPE_TMP_BUFFER);
939
        if (workingConfig->raw == NULL) {
940
            ret = MEMORY_E;
941
            break;
942
        }
943
944
        XMEMCPY(workingConfig->raw, echConfig, workingConfig->rawLen);
945
946
        /* skip over version and length */
947
        echConfig += 4;
948
949
        /* configId, 1 byte */
950
        workingConfig->configId = *(echConfig);
951
        echConfig++;
952
        /* kemId, 2 bytes */
953
        ato16(echConfig, &workingConfig->kemId);
954
        echConfig += 2;
955
        /* hpke public_key length, 2 bytes */
956
        ato16(echConfig, &hpkePubkeyLen);
957
        echConfig += 2;
958
        /* hpke public_key */
959
        XMEMCPY(workingConfig->receiverPubkey, echConfig, hpkePubkeyLen);
960
        echConfig += hpkePubkeyLen;
961
        /* cipherSuitesLen */
962
        ato16(echConfig, &cipherSuitesLen);
963
964
        workingConfig->cipherSuites = (EchCipherSuite*)XMALLOC(cipherSuitesLen,
965
            heap, DYNAMIC_TYPE_TMP_BUFFER);
966
        if (workingConfig->cipherSuites == NULL) {
967
            ret = MEMORY_E;
968
            break;
969
        }
970
971
        echConfig += 2;
972
        workingConfig->numCipherSuites = cipherSuitesLen / 4;
973
        /* cipherSuites */
974
        for (j = 0; j < workingConfig->numCipherSuites; j++) {
975
            ato16(echConfig + j * 4, &workingConfig->cipherSuites[j].kdfId);
976
            ato16(echConfig + j * 4 + 2,
977
                &workingConfig->cipherSuites[j].aeadId);
978
        }
979
        echConfig += cipherSuitesLen;
980
        /* ignore the maximum name length */
981
        echConfig++;
982
        /* publicNameLen */
983
        publicNameLen = *(echConfig);
984
        workingConfig->publicName = (char*)XMALLOC(publicNameLen + 1,
985
            heap, DYNAMIC_TYPE_TMP_BUFFER);
986
        if (workingConfig->publicName == NULL) {
987
            ret = MEMORY_E;
988
            break;
989
        }
990
        echConfig++;
991
        /* publicName */
992
        XMEMCPY(workingConfig->publicName, echConfig, publicNameLen);
993
        /* null terminated */
994
        workingConfig->publicName[publicNameLen] = 0;
995
996
        /* add length to go to next config, +4 for version and length */
997
        i += length + 4;
998
999
        /* check that we support this config */
1000
        for (j = 0; j < HPKE_SUPPORTED_KEM_LEN; j++) {
1001
            if (hpkeSupportedKem[j] == workingConfig->kemId)
1002
                break;
1003
        }
1004
1005
        /* if we don't support the kem or at least one cipher suite */
1006
        if (j >= HPKE_SUPPORTED_KEM_LEN ||
1007
            EchConfigGetSupportedCipherSuite(workingConfig) < 0)
1008
        {
1009
            XFREE(workingConfig->cipherSuites, heap,
1010
                DYNAMIC_TYPE_TMP_BUFFER);
1011
            XFREE(workingConfig->publicName, heap,
1012
                DYNAMIC_TYPE_TMP_BUFFER);
1013
            XFREE(workingConfig->raw, heap, DYNAMIC_TYPE_TMP_BUFFER);
1014
            workingConfig = lastConfig;
1015
        }
1016
    } while ((word32)i < echConfigsLen);
1017
1018
    /* if we found valid configs */
1019
    if (ret == 0 && configList != NULL) {
1020
        *outputConfigs = configList;
1021
1022
        return ret;
1023
    }
1024
1025
    workingConfig = configList;
1026
1027
    while (workingConfig != NULL) {
1028
        lastConfig = workingConfig;
1029
        workingConfig = workingConfig->next;
1030
1031
        XFREE(lastConfig->cipherSuites, heap, DYNAMIC_TYPE_TMP_BUFFER);
1032
        XFREE(lastConfig->publicName, heap, DYNAMIC_TYPE_TMP_BUFFER);
1033
        XFREE(lastConfig->raw, heap, DYNAMIC_TYPE_TMP_BUFFER);
1034
1035
        XFREE(lastConfig, heap, DYNAMIC_TYPE_TMP_BUFFER);
1036
    }
1037
1038
    if (ret == 0)
1039
        return WOLFSSL_FATAL_ERROR;
1040
1041
    return ret;
1042
}
1043
1044
/* get the raw ech configs from our linked list of ech config structs */
1045
int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen)
1046
{
1047
    int ret = 0;
1048
    WOLFSSL_EchConfig* workingConfig = NULL;
1049
    byte* outputStart = output;
1050
    word32 totalLen = 2;
1051
    word32 workingOutputLen = 0;
1052
1053
    if (configs == NULL || outputLen == NULL ||
1054
            (output != NULL && *outputLen < totalLen)) {
1055
        return BAD_FUNC_ARG;
1056
    }
1057
1058
1059
    /* skip over total length which we fill in later */
1060
    if (output != NULL) {
1061
        workingOutputLen = *outputLen - totalLen;
1062
        output += 2;
1063
    }
1064
    else {
1065
        /* caller getting the size only, set current 2 byte length size */
1066
        *outputLen = totalLen;
1067
    }
1068
1069
    workingConfig = configs;
1070
1071
    while (workingConfig != NULL) {
1072
        /* get this config */
1073
        ret = GetEchConfig(workingConfig, output, &workingOutputLen);
1074
1075
        if (output != NULL)
1076
            output += workingOutputLen;
1077
1078
        /* add this config's length to the total length */
1079
        totalLen += workingOutputLen;
1080
1081
        if (totalLen > *outputLen)
1082
            workingOutputLen = 0;
1083
        else
1084
            workingOutputLen = *outputLen - totalLen;
1085
1086
        /* only error we break on, other 2 we need to keep finding length */
1087
        if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG))
1088
            return BAD_FUNC_ARG;
1089
1090
        workingConfig = workingConfig->next;
1091
    }
1092
1093
    if (output == NULL) {
1094
        *outputLen = totalLen;
1095
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
1096
    }
1097
1098
    if (totalLen > *outputLen) {
1099
        *outputLen = totalLen;
1100
        return INPUT_SIZE_E;
1101
    }
1102
1103
    /* total size -2 for size itself */
1104
    c16toa(totalLen - 2, outputStart);
1105
1106
    *outputLen = totalLen;
1107
1108
    return WOLFSSL_SUCCESS;
1109
}
1110
#endif /* WOLFSSL_TLS13 && HAVE_ECH */
1111
1112
#ifdef OPENSSL_EXTRA
1113
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
1114
        Suites* suites, const char* list);
1115
#endif
1116
1117
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
1118
#include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
1119
#endif
1120
1121
/* prevent multiple mutex initializations */
1122
static volatile WC_THREADSHARED int initRefCount = 0;
1123
/* init ref count mutex */
1124
static WC_THREADSHARED wolfSSL_Mutex inits_count_mutex
1125
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex);
1126
#ifndef WOLFSSL_MUTEX_INITIALIZER
1127
static WC_THREADSHARED volatile int inits_count_mutex_valid = 0;
1128
#endif
1129
1130
#ifdef NO_TLS
1131
static const WOLFSSL_METHOD gNoTlsMethod;
1132
#endif
1133
1134
/* Create a new WOLFSSL_CTX struct and return the pointer to created struct.
1135
   WOLFSSL_METHOD pointer passed in is given to ctx to manage.
1136
   This function frees the passed in WOLFSSL_METHOD struct on failure and on
1137
   success is freed when ctx is freed.
1138
 */
1139
WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap)
1140
4.85k
{
1141
4.85k
    WOLFSSL_CTX* ctx = NULL;
1142
1143
4.85k
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
1144
1145
4.85k
    if (initRefCount == 0) {
1146
        /* user no longer forced to call Init themselves */
1147
0
        int ret = wolfSSL_Init();
1148
0
        if (ret != WOLFSSL_SUCCESS) {
1149
0
            WOLFSSL_MSG("wolfSSL_Init failed");
1150
0
            WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
1151
0
            XFREE(method, heap, DYNAMIC_TYPE_METHOD);
1152
0
            return NULL;
1153
0
        }
1154
0
    }
1155
1156
4.85k
#ifndef NO_TLS
1157
4.85k
    if (method == NULL)
1158
0
        return ctx;
1159
#else
1160
    /* a blank TLS method */
1161
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
1162
#endif
1163
1164
4.85k
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
1165
4.85k
    if (ctx) {
1166
4.85k
        int ret;
1167
1168
4.85k
        ret = InitSSL_Ctx(ctx, method, heap);
1169
    #ifdef WOLFSSL_STATIC_MEMORY
1170
        if (heap != NULL) {
1171
            ctx->onHeapHint = 1; /* free the memory back to heap when done */
1172
        }
1173
    #endif
1174
4.85k
        if (ret < 0) {
1175
0
            WOLFSSL_MSG("Init CTX failed");
1176
0
            wolfSSL_CTX_free(ctx);
1177
0
            ctx = NULL;
1178
0
        }
1179
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
1180
                           && !defined(NO_SHA256) && !defined(WC_NO_RNG)
1181
        else {
1182
            ctx->srp = (Srp*)XMALLOC(sizeof(Srp), heap, DYNAMIC_TYPE_SRP);
1183
            if (ctx->srp == NULL){
1184
                WOLFSSL_MSG("Init CTX failed");
1185
                wolfSSL_CTX_free(ctx);
1186
                return NULL;
1187
            }
1188
            XMEMSET(ctx->srp, 0, sizeof(Srp));
1189
        }
1190
#endif
1191
4.85k
    }
1192
0
    else {
1193
0
        WOLFSSL_MSG("Alloc CTX failed, method freed");
1194
0
        XFREE(method, heap, DYNAMIC_TYPE_METHOD);
1195
0
    }
1196
1197
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
1198
    if (ctx) {
1199
        wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, NULL);
1200
        wolfSSL_CTX_set_mode(ctx, WOLFSSL_MODE_AUTO_RETRY);
1201
        if (wolfSSL_CTX_set_min_proto_version(ctx,
1202
                (method->version.major == DTLS_MAJOR) ?
1203
                DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS ||
1204
#ifdef HAVE_ANON
1205
                wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS ||
1206
#endif
1207
                wolfSSL_CTX_set_group_messages(ctx) != WOLFSSL_SUCCESS) {
1208
            WOLFSSL_MSG("Setting OpenSSL CTX defaults failed");
1209
            wolfSSL_CTX_free(ctx);
1210
            ctx = NULL;
1211
        }
1212
    }
1213
#endif
1214
1215
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
1216
    /* Load the crypto-policy ciphers if configured. */
1217
    if (ctx && wolfSSL_crypto_policy_is_enabled()) {
1218
        const char * list = wolfSSL_crypto_policy_get_ciphers();
1219
        int          ret = 0;
1220
1221
        if (list != NULL && *list != '\0') {
1222
            if (AllocateCtxSuites(ctx) != 0) {
1223
                WOLFSSL_MSG("allocate ctx suites failed");
1224
                wolfSSL_CTX_free(ctx);
1225
                ctx = NULL;
1226
            }
1227
            else {
1228
                ret = wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
1229
                if (ret != WOLFSSL_SUCCESS) {
1230
                    WOLFSSL_MSG("parse cipher list failed");
1231
                    wolfSSL_CTX_free(ctx);
1232
                    ctx = NULL;
1233
                }
1234
            }
1235
        }
1236
    }
1237
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
1238
1239
4.85k
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
1240
4.85k
    return ctx;
1241
4.85k
}
1242
1243
1244
WOLFSSL_ABI
1245
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
1246
4.90k
{
1247
#ifdef WOLFSSL_HEAP_TEST
1248
    /* if testing the heap hint then set top level CTX to have test value */
1249
    return wolfSSL_CTX_new_ex(method, (void*)WOLFSSL_HEAP_TEST);
1250
#else
1251
4.90k
    return wolfSSL_CTX_new_ex(method, NULL);
1252
4.90k
#endif
1253
4.90k
}
1254
1255
/* increases CTX reference count to track proper time to "free" */
1256
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
1257
78.8k
{
1258
78.8k
    int ret;
1259
78.8k
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
1260
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
1261
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
1262
#else
1263
78.8k
    (void)ret;
1264
78.8k
    return WOLFSSL_SUCCESS;
1265
78.8k
#endif
1266
78.8k
}
1267
1268
WOLFSSL_ABI
1269
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
1270
4.85k
{
1271
4.85k
    WOLFSSL_ENTER("wolfSSL_CTX_free");
1272
4.85k
    if (ctx) {
1273
4.85k
        FreeSSL_Ctx(ctx);
1274
4.85k
    }
1275
1276
4.85k
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
1277
4.85k
}
1278
1279
1280
#ifdef HAVE_ENCRYPT_THEN_MAC
1281
/**
1282
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
1283
 * The default value: enabled.
1284
 *
1285
 * ctx  SSL/TLS context.
1286
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
1287
 * returns WOLFSSL_SUCCESS
1288
 */
1289
int wolfSSL_CTX_AllowEncryptThenMac(WOLFSSL_CTX *ctx, int set)
1290
0
{
1291
0
    ctx->disallowEncThenMac = !set;
1292
0
    return WOLFSSL_SUCCESS;
1293
0
}
1294
1295
/**
1296
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
1297
 * The default value comes from context.
1298
 *
1299
 * ctx  SSL/TLS context.
1300
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
1301
 * returns WOLFSSL_SUCCESS
1302
 */
1303
int wolfSSL_AllowEncryptThenMac(WOLFSSL *ssl, int set)
1304
0
{
1305
0
    ssl->options.disallowEncThenMac = !set;
1306
0
    return WOLFSSL_SUCCESS;
1307
0
}
1308
#endif
1309
1310
#ifdef SINGLE_THREADED
1311
/* no locking in single threaded mode, allow a CTX level rng to be shared with
1312
 * WOLFSSL objects, WOLFSSL_SUCCESS on ok */
1313
int wolfSSL_CTX_new_rng(WOLFSSL_CTX* ctx)
1314
{
1315
    WC_RNG* rng;
1316
    int     ret;
1317
1318
    if (ctx == NULL) {
1319
        return BAD_FUNC_ARG;
1320
    }
1321
1322
    rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ctx->heap, DYNAMIC_TYPE_RNG);
1323
    if (rng == NULL) {
1324
        return MEMORY_E;
1325
    }
1326
1327
#ifndef HAVE_FIPS
1328
    ret = wc_InitRng_ex(rng, ctx->heap, ctx->devId);
1329
#else
1330
    ret = wc_InitRng(rng);
1331
#endif
1332
    if (ret != 0) {
1333
        XFREE(rng, ctx->heap, DYNAMIC_TYPE_RNG);
1334
        return ret;
1335
    }
1336
1337
    ctx->rng = rng;
1338
    return WOLFSSL_SUCCESS;
1339
}
1340
#endif
1341
1342
1343
WOLFSSL_ABI
1344
WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx)
1345
79.0k
{
1346
79.0k
    WOLFSSL* ssl = NULL;
1347
79.0k
    int ret = 0;
1348
1349
79.0k
    WOLFSSL_ENTER("wolfSSL_new");
1350
1351
79.0k
    if (ctx == NULL) {
1352
0
        WOLFSSL_MSG("wolfSSL_new ctx is null");
1353
0
        return NULL;
1354
0
    }
1355
1356
79.0k
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
1357
1358
79.0k
    if (ssl == NULL) {
1359
14
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
1360
14
                        (int)sizeof(WOLFSSL));
1361
14
    }
1362
79.0k
    else {
1363
79.0k
        ret = InitSSL(ssl, ctx, 0);
1364
79.0k
        if (ret < 0) {
1365
4.57k
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
1366
4.57k
            FreeSSL(ssl, ctx->heap);
1367
4.57k
            ssl = NULL;
1368
4.57k
        }
1369
74.4k
        else if (ret == 0) {
1370
74.4k
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
1371
74.4k
        }
1372
0
        else {
1373
            /* Only success (0) or negative values should ever be seen. */
1374
0
            WOLFSSL_MSG_EX("WARNING: wolfSSL_new unexpected InitSSL return"
1375
0
                           " value = %d", ret);
1376
0
        } /* InitSSL check */
1377
79.0k
    } /* ssl XMALLOC success */
1378
1379
79.0k
    WOLFSSL_LEAVE("wolfSSL_new InitSSL =", ret);
1380
79.0k
    (void)ret;
1381
1382
79.0k
    return ssl;
1383
79.0k
}
1384
1385
1386
WOLFSSL_ABI
1387
void wolfSSL_free(WOLFSSL* ssl)
1388
74.5k
{
1389
74.5k
    WOLFSSL_ENTER("wolfSSL_free");
1390
1391
74.5k
    if (ssl) {
1392
74.4k
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
1393
74.4k
        FreeSSL(ssl, ssl->ctx->heap);
1394
74.4k
    }
1395
119
    else {
1396
119
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
1397
119
    }
1398
74.5k
    WOLFSSL_LEAVE("wolfSSL_free", 0);
1399
74.5k
}
1400
1401
1402
int wolfSSL_is_server(WOLFSSL* ssl)
1403
0
{
1404
0
    if (ssl == NULL)
1405
0
        return BAD_FUNC_ARG;
1406
0
    return ssl->options.side == WOLFSSL_SERVER_END;
1407
0
}
1408
1409
#ifdef HAVE_WRITE_DUP
1410
1411
/*
1412
 * Release resources around WriteDup object
1413
 *
1414
 * ssl WOLFSSL object
1415
 *
1416
 * no return, destruction so make best attempt
1417
*/
1418
void FreeWriteDup(WOLFSSL* ssl)
1419
{
1420
    int doFree = 0;
1421
1422
    WOLFSSL_ENTER("FreeWriteDup");
1423
1424
    if (ssl->dupWrite) {
1425
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) == 0) {
1426
            ssl->dupWrite->dupCount--;
1427
            if (ssl->dupWrite->dupCount == 0) {
1428
                doFree = 1;
1429
            } else {
1430
                WOLFSSL_MSG("WriteDup count not zero, no full free");
1431
            }
1432
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1433
        }
1434
    }
1435
1436
    if (doFree) {
1437
        WOLFSSL_MSG("Doing WriteDup full free, count to zero");
1438
        wc_FreeMutex(&ssl->dupWrite->dupMutex);
1439
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
1440
    }
1441
}
1442
1443
1444
/*
1445
 * duplicate existing ssl members into dup needed for writing
1446
 *
1447
 * dup write only WOLFSSL
1448
 * ssl existing WOLFSSL
1449
 *
1450
 * 0 on success
1451
*/
1452
static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
1453
{
1454
    word16 tmp_weOwnRng;
1455
1456
    /* shared dupWrite setup */
1457
    ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
1458
                                       DYNAMIC_TYPE_WRITEDUP);
1459
    if (ssl->dupWrite == NULL) {
1460
        return MEMORY_E;
1461
    }
1462
    XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
1463
1464
    if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
1465
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
1466
        ssl->dupWrite = NULL;
1467
        return BAD_MUTEX_E;
1468
    }
1469
    ssl->dupWrite->dupCount = 2;    /* both sides have a count to start */
1470
    dup->dupWrite = ssl->dupWrite; /* each side uses */
1471
1472
    tmp_weOwnRng = dup->options.weOwnRng;
1473
1474
    /* copy write parts over to dup writer */
1475
    XMEMCPY(&dup->specs,   &ssl->specs,   sizeof(CipherSpecs));
1476
    XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
1477
    XMEMCPY(&dup->keys,    &ssl->keys,    sizeof(Keys));
1478
    XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
1479
    XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
1480
    XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
1481
1482
#ifdef HAVE_ONE_TIME_AUTH
1483
#ifdef HAVE_POLY1305
1484
    if (ssl->auth.setup && ssl->auth.poly1305 != NULL) {
1485
        dup->auth.poly1305 = (Poly1305*)XMALLOC(sizeof(Poly1305), dup->heap,
1486
            DYNAMIC_TYPE_CIPHER);
1487
        if (dup->auth.poly1305 == NULL)
1488
            return MEMORY_E;
1489
        dup->auth.setup = 1;
1490
    }
1491
#endif
1492
#endif
1493
1494
    /* dup side now owns encrypt/write ciphers */
1495
    XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
1496
1497
    dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
1498
    dup->CBIOSend = ssl->CBIOSend;
1499
#ifdef OPENSSL_EXTRA
1500
    dup->cbioFlag = ssl->cbioFlag;
1501
#endif
1502
    dup->wfd    = ssl->wfd;
1503
    dup->wflags = ssl->wflags;
1504
#ifndef WOLFSSL_AEAD_ONLY
1505
    dup->hmac   = ssl->hmac;
1506
#endif
1507
#ifdef HAVE_TRUNCATED_HMAC
1508
    dup->truncated_hmac = ssl->truncated_hmac;
1509
#endif
1510
1511
    /* Restore rng option */
1512
    dup->options.weOwnRng = tmp_weOwnRng;
1513
1514
    /* unique side dup setup */
1515
    dup->dupSide = WRITE_DUP_SIDE;
1516
    ssl->dupSide = READ_DUP_SIDE;
1517
1518
    return 0;
1519
}
1520
1521
1522
/*
1523
 * duplicate a WOLFSSL object post handshake for writing only
1524
 * turn existing object into read only.  Allows concurrent access from two
1525
 * different threads.
1526
 *
1527
 * ssl existing WOLFSSL object
1528
 *
1529
 * return dup'd WOLFSSL object on success
1530
*/
1531
WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
1532
{
1533
    WOLFSSL* dup = NULL;
1534
    int ret = 0;
1535
1536
    (void)ret;
1537
    WOLFSSL_ENTER("wolfSSL_write_dup");
1538
1539
    if (ssl == NULL) {
1540
        return ssl;
1541
    }
1542
1543
    if (ssl->options.handShakeDone == 0) {
1544
        WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
1545
        return NULL;
1546
    }
1547
1548
    if (ssl->dupWrite) {
1549
        WOLFSSL_MSG("wolfSSL_write_dup already called once");
1550
        return NULL;
1551
    }
1552
1553
    dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
1554
    if (dup) {
1555
        if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
1556
            FreeSSL(dup, ssl->ctx->heap);
1557
            dup = NULL;
1558
        } else if ( (ret = DupSSL(dup, ssl)) < 0) {
1559
            FreeSSL(dup, ssl->ctx->heap);
1560
            dup = NULL;
1561
        }
1562
    }
1563
1564
    WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
1565
1566
    return dup;
1567
}
1568
1569
1570
/*
1571
 * Notify write dup side of fatal error or close notify
1572
 *
1573
 * ssl WOLFSSL object
1574
 * err Notify err
1575
 *
1576
 * 0 on success
1577
*/
1578
int NotifyWriteSide(WOLFSSL* ssl, int err)
1579
{
1580
    int ret;
1581
1582
    WOLFSSL_ENTER("NotifyWriteSide");
1583
1584
    ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
1585
    if (ret == 0) {
1586
        ssl->dupWrite->dupErr = err;
1587
        ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1588
    }
1589
1590
    return ret;
1591
}
1592
1593
1594
#endif /* HAVE_WRITE_DUP */
1595
1596
1597
#ifdef HAVE_POLY1305
1598
/* set if to use old poly 1 for yes 0 to use new poly */
1599
int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
1600
0
{
1601
0
    (void)ssl;
1602
0
    (void)value;
1603
1604
0
#ifndef WOLFSSL_NO_TLS12
1605
0
    WOLFSSL_ENTER("wolfSSL_use_old_poly");
1606
0
    WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
1607
0
            "is depreciated");
1608
0
    ssl->options.oldPoly = (word16)value;
1609
0
    WOLFSSL_LEAVE("wolfSSL_use_old_poly", 0);
1610
0
#endif
1611
0
    return 0;
1612
0
}
1613
#endif
1614
1615
1616
WOLFSSL_ABI
1617
int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
1618
0
{
1619
0
    int ret;
1620
1621
0
    WOLFSSL_ENTER("wolfSSL_set_fd");
1622
1623
0
    if (ssl == NULL) {
1624
0
        return BAD_FUNC_ARG;
1625
0
    }
1626
1627
0
    ret = wolfSSL_set_read_fd(ssl, fd);
1628
0
    if (ret == WOLFSSL_SUCCESS) {
1629
0
        ret = wolfSSL_set_write_fd(ssl, fd);
1630
0
    }
1631
1632
0
    return ret;
1633
0
}
1634
1635
#ifdef WOLFSSL_DTLS
1636
int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd)
1637
{
1638
    int ret;
1639
1640
    WOLFSSL_ENTER("wolfSSL_set_dtls_fd_connected");
1641
1642
    if (ssl == NULL) {
1643
        return BAD_FUNC_ARG;
1644
    }
1645
1646
    ret = wolfSSL_set_fd(ssl, fd);
1647
    if (ret == WOLFSSL_SUCCESS)
1648
        ssl->buffers.dtlsCtx.connected = 1;
1649
1650
    return ret;
1651
}
1652
#endif
1653
1654
1655
int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
1656
0
{
1657
0
    WOLFSSL_ENTER("wolfSSL_set_read_fd");
1658
1659
0
    if (ssl == NULL) {
1660
0
        return BAD_FUNC_ARG;
1661
0
    }
1662
1663
0
    ssl->rfd = fd;      /* not used directly to allow IO callbacks */
1664
0
    ssl->IOCB_ReadCtx  = &ssl->rfd;
1665
1666
    #ifdef WOLFSSL_DTLS
1667
        ssl->buffers.dtlsCtx.connected = 0;
1668
        if (ssl->options.dtls) {
1669
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
1670
            ssl->buffers.dtlsCtx.rfd = fd;
1671
        }
1672
    #endif
1673
1674
0
    WOLFSSL_LEAVE("wolfSSL_set_read_fd", WOLFSSL_SUCCESS);
1675
0
    return WOLFSSL_SUCCESS;
1676
0
}
1677
1678
1679
int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
1680
0
{
1681
0
    WOLFSSL_ENTER("wolfSSL_set_write_fd");
1682
1683
0
    if (ssl == NULL) {
1684
0
        return BAD_FUNC_ARG;
1685
0
    }
1686
1687
0
    ssl->wfd = fd;      /* not used directly to allow IO callbacks */
1688
0
    ssl->IOCB_WriteCtx  = &ssl->wfd;
1689
1690
    #ifdef WOLFSSL_DTLS
1691
        ssl->buffers.dtlsCtx.connected = 0;
1692
        if (ssl->options.dtls) {
1693
            ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
1694
            ssl->buffers.dtlsCtx.wfd = fd;
1695
        }
1696
    #endif
1697
1698
0
    WOLFSSL_LEAVE("wolfSSL_set_write_fd", WOLFSSL_SUCCESS);
1699
0
    return WOLFSSL_SUCCESS;
1700
0
}
1701
1702
1703
/**
1704
  * Get the name of cipher at priority level passed in.
1705
  */
1706
char* wolfSSL_get_cipher_list(int priority)
1707
0
{
1708
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1709
1710
0
    if (priority >= GetCipherNamesSize() || priority < 0) {
1711
0
        return 0;
1712
0
    }
1713
1714
0
    return (char*)ciphers[priority].name;
1715
0
}
1716
1717
1718
/**
1719
  * Get the name of cipher at priority level passed in.
1720
  */
1721
char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
1722
0
{
1723
1724
0
    if (ssl == NULL) {
1725
0
        return NULL;
1726
0
    }
1727
0
    else {
1728
0
        const char* cipher;
1729
1730
0
        if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
1731
0
            if (priority == 0) {
1732
0
                return (char*)cipher;
1733
0
            }
1734
0
            else {
1735
0
                return NULL;
1736
0
            }
1737
0
        }
1738
0
        else {
1739
0
            return wolfSSL_get_cipher_list(priority);
1740
0
        }
1741
0
    }
1742
0
}
1743
1744
1745
int wolfSSL_get_ciphers(char* buf, int len)
1746
0
{
1747
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1748
0
    int ciphersSz = GetCipherNamesSize();
1749
0
    int i;
1750
1751
0
    if (buf == NULL || len <= 0)
1752
0
        return BAD_FUNC_ARG;
1753
1754
    /* Add each member to the buffer delimited by a : */
1755
0
    for (i = 0; i < ciphersSz; i++) {
1756
0
        int cipherNameSz = (int)XSTRLEN(ciphers[i].name);
1757
0
        if (cipherNameSz + 1 < len) {
1758
0
            XSTRNCPY(buf, ciphers[i].name, (size_t)len);
1759
0
            buf += cipherNameSz;
1760
1761
0
            if (i < ciphersSz - 1)
1762
0
                *buf++ = ':';
1763
0
            *buf = 0;
1764
1765
0
            len -= cipherNameSz + 1;
1766
0
        }
1767
0
        else
1768
0
            return BUFFER_E;
1769
0
    }
1770
0
    return WOLFSSL_SUCCESS;
1771
0
}
1772
1773
1774
#ifndef NO_ERROR_STRINGS
1775
/* places a list of all supported cipher suites in TLS_* format into "buf"
1776
 * return WOLFSSL_SUCCESS on success */
1777
int wolfSSL_get_ciphers_iana(char* buf, int len)
1778
0
{
1779
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1780
0
    int ciphersSz = GetCipherNamesSize();
1781
0
    int i;
1782
0
    int cipherNameSz;
1783
1784
0
    if (buf == NULL || len <= 0)
1785
0
        return BAD_FUNC_ARG;
1786
1787
    /* Add each member to the buffer delimited by a : */
1788
0
    for (i = 0; i < ciphersSz; i++) {
1789
0
#ifndef NO_CIPHER_SUITE_ALIASES
1790
0
        if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
1791
0
            continue;
1792
0
#endif
1793
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
1794
0
        if (cipherNameSz + 1 < len) {
1795
0
            XSTRNCPY(buf, ciphers[i].name_iana, (size_t)len);
1796
0
            buf += cipherNameSz;
1797
1798
0
            if (i < ciphersSz - 1)
1799
0
                *buf++ = ':';
1800
0
            *buf = 0;
1801
1802
0
            len -= cipherNameSz + 1;
1803
0
        }
1804
0
        else
1805
0
            return BUFFER_E;
1806
0
    }
1807
0
    return WOLFSSL_SUCCESS;
1808
0
}
1809
#endif /* NO_ERROR_STRINGS */
1810
1811
1812
const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
1813
0
{
1814
0
    const char* cipher;
1815
1816
0
    if (ssl == NULL)
1817
0
        return NULL;
1818
1819
0
    cipher = wolfSSL_get_cipher_name_iana(ssl);
1820
0
    len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1));
1821
0
    XMEMCPY(buf, cipher, (size_t)len);
1822
0
    return buf;
1823
0
}
1824
1825
int wolfSSL_get_fd(const WOLFSSL* ssl)
1826
0
{
1827
0
    int fd = -1;
1828
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1829
0
    if (ssl) {
1830
0
        fd = ssl->rfd;
1831
0
    }
1832
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1833
0
    return fd;
1834
0
}
1835
1836
int wolfSSL_get_wfd(const WOLFSSL* ssl)
1837
0
{
1838
0
    int fd = -1;
1839
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1840
0
    if (ssl) {
1841
0
        fd = ssl->wfd;
1842
0
    }
1843
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1844
0
    return fd;
1845
0
}
1846
1847
1848
int wolfSSL_dtls(WOLFSSL* ssl)
1849
0
{
1850
0
    int dtlsOpt = 0;
1851
0
    if (ssl)
1852
0
        dtlsOpt = ssl->options.dtls;
1853
0
    return dtlsOpt;
1854
0
}
1855
1856
#if !defined(NO_CERTS)
1857
/* Set whether mutual authentication is required for connections.
1858
 * Server side only.
1859
 *
1860
 * ctx  The SSL/TLS CTX object.
1861
 * req  1 to indicate required and 0 when not.
1862
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
1863
 * 0 on success.
1864
 */
1865
int wolfSSL_CTX_mutual_auth(WOLFSSL_CTX* ctx, int req)
1866
0
{
1867
0
    if (ctx == NULL)
1868
0
        return BAD_FUNC_ARG;
1869
0
    if (ctx->method->side != WOLFSSL_SERVER_END)
1870
0
        return SIDE_ERROR;
1871
1872
0
    ctx->mutualAuth = (byte)req;
1873
1874
0
    return 0;
1875
0
}
1876
1877
/* Set whether mutual authentication is required for the connection.
1878
 * Server side only.
1879
 *
1880
 * ssl  The SSL/TLS object.
1881
 * req  1 to indicate required and 0 when not.
1882
 * returns BAD_FUNC_ARG when ssl is NULL and
1883
 * SIDE_ERROR when not a server and 0 on success.
1884
 */
1885
int wolfSSL_mutual_auth(WOLFSSL* ssl, int req)
1886
0
{
1887
0
    if (ssl == NULL)
1888
0
        return BAD_FUNC_ARG;
1889
0
    if (ssl->options.side != WOLFSSL_SERVER_END)
1890
0
        return SIDE_ERROR;
1891
1892
0
    ssl->options.mutualAuth = (word16)req;
1893
1894
0
    return 0;
1895
0
}
1896
#endif /* NO_CERTS */
1897
1898
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
1899
1900
int wolfSSL_CTX_set_AcceptFilter(
1901
    WOLFSSL_CTX *ctx,
1902
    NetworkFilterCallback_t AcceptFilter,
1903
    void *AcceptFilter_arg)
1904
{
1905
    if (ctx == NULL)
1906
        return BAD_FUNC_ARG;
1907
    ctx->AcceptFilter = AcceptFilter;
1908
    ctx->AcceptFilter_arg = AcceptFilter_arg;
1909
    return 0;
1910
}
1911
1912
int wolfSSL_set_AcceptFilter(
1913
    WOLFSSL *ssl,
1914
    NetworkFilterCallback_t AcceptFilter,
1915
    void *AcceptFilter_arg)
1916
{
1917
    if (ssl == NULL)
1918
        return BAD_FUNC_ARG;
1919
    ssl->AcceptFilter = AcceptFilter;
1920
    ssl->AcceptFilter_arg = AcceptFilter_arg;
1921
    return 0;
1922
}
1923
1924
int wolfSSL_CTX_set_ConnectFilter(
1925
    WOLFSSL_CTX *ctx,
1926
    NetworkFilterCallback_t ConnectFilter,
1927
    void *ConnectFilter_arg)
1928
{
1929
    if (ctx == NULL)
1930
        return BAD_FUNC_ARG;
1931
    ctx->ConnectFilter = ConnectFilter;
1932
    ctx->ConnectFilter_arg = ConnectFilter_arg;
1933
    return 0;
1934
}
1935
1936
int wolfSSL_set_ConnectFilter(
1937
    WOLFSSL *ssl,
1938
    NetworkFilterCallback_t ConnectFilter,
1939
    void *ConnectFilter_arg)
1940
{
1941
    if (ssl == NULL)
1942
        return BAD_FUNC_ARG;
1943
    ssl->ConnectFilter = ConnectFilter;
1944
    ssl->ConnectFilter_arg = ConnectFilter_arg;
1945
    return 0;
1946
}
1947
1948
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
1949
1950
#ifndef WOLFSSL_LEANPSK
1951
#if defined(WOLFSSL_DTLS) && defined(XINET_PTON) && \
1952
    !defined(WOLFSSL_NO_SOCK) && defined(HAVE_SOCKADDR)
1953
void* wolfSSL_dtls_create_peer(int port, char* ip)
1954
{
1955
    SOCKADDR_IN *addr;
1956
    addr = (SOCKADDR_IN*)XMALLOC(sizeof(*addr), NULL,
1957
            DYNAMIC_TYPE_SOCKADDR);
1958
    if (addr == NULL) {
1959
        return NULL;
1960
    }
1961
1962
    addr->sin_family = AF_INET;
1963
    addr->sin_port = XHTONS((word16)port);
1964
    if (XINET_PTON(AF_INET, ip, &addr->sin_addr) < 1) {
1965
        XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1966
        return NULL;
1967
    }
1968
1969
    return addr;
1970
}
1971
1972
int wolfSSL_dtls_free_peer(void* addr)
1973
{
1974
    XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1975
    return WOLFSSL_SUCCESS;
1976
}
1977
#endif
1978
1979
#ifdef WOLFSSL_DTLS
1980
static int SockAddrSet(WOLFSSL_SOCKADDR* sockAddr, void* peer,
1981
                       unsigned int peerSz, void* heap)
1982
{
1983
    if (peer == NULL || peerSz == 0) {
1984
        if (sockAddr->sa != NULL)
1985
            XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR);
1986
        sockAddr->sa = NULL;
1987
        sockAddr->sz = 0;
1988
        sockAddr->bufSz = 0;
1989
        return WOLFSSL_SUCCESS;
1990
    }
1991
1992
    if (peerSz > sockAddr->bufSz) {
1993
        if (sockAddr->sa != NULL)
1994
            XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR);
1995
        sockAddr->sa =
1996
                (void*)XMALLOC(peerSz, heap, DYNAMIC_TYPE_SOCKADDR);
1997
        if (sockAddr->sa == NULL) {
1998
            sockAddr->sz = 0;
1999
            sockAddr->bufSz = 0;
2000
            return WOLFSSL_FAILURE;
2001
        }
2002
        sockAddr->bufSz = peerSz;
2003
    }
2004
    XMEMCPY(sockAddr->sa, peer, peerSz);
2005
    sockAddr->sz = peerSz;
2006
    return WOLFSSL_SUCCESS;
2007
}
2008
#endif
2009
2010
int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
2011
0
{
2012
#ifdef WOLFSSL_DTLS
2013
    int ret;
2014
2015
    if (ssl == NULL)
2016
        return WOLFSSL_FAILURE;
2017
#ifdef WOLFSSL_RW_THREADED
2018
    if (wc_LockRwLock_Wr(&ssl->buffers.dtlsCtx.peerLock) != 0)
2019
        return WOLFSSL_FAILURE;
2020
#endif
2021
    ret = SockAddrSet(&ssl->buffers.dtlsCtx.peer, peer, peerSz, ssl->heap);
2022
    if (ret == WOLFSSL_SUCCESS && !(peer == NULL || peerSz == 0))
2023
        ssl->buffers.dtlsCtx.userSet = 1;
2024
    else
2025
        ssl->buffers.dtlsCtx.userSet = 0;
2026
#ifdef WOLFSSL_RW_THREADED
2027
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
2028
        ret = WOLFSSL_FAILURE;
2029
#endif
2030
    return ret;
2031
#else
2032
0
    (void)ssl;
2033
0
    (void)peer;
2034
0
    (void)peerSz;
2035
0
    return WOLFSSL_NOT_IMPLEMENTED;
2036
0
#endif
2037
0
}
2038
2039
#if defined(WOLFSSL_DTLS_CID) && !defined(WOLFSSL_NO_SOCK)
2040
int wolfSSL_dtls_set_pending_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
2041
{
2042
#ifdef WOLFSSL_DTLS
2043
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
2044
2045
    if (ssl == NULL)
2046
        return WOLFSSL_FAILURE;
2047
#ifdef WOLFSSL_RW_THREADED
2048
    if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0)
2049
        return WOLFSSL_FAILURE;
2050
#endif
2051
    if (ssl->buffers.dtlsCtx.peer.sa != NULL &&
2052
            ssl->buffers.dtlsCtx.peer.sz == peerSz &&
2053
            sockAddrEqual((SOCKADDR_S*)ssl->buffers.dtlsCtx.peer.sa,
2054
                    (XSOCKLENT)ssl->buffers.dtlsCtx.peer.sz, (SOCKADDR_S*)peer,
2055
                    (XSOCKLENT)peerSz)) {
2056
        /* Already the current peer. */
2057
        if (ssl->buffers.dtlsCtx.pendingPeer.sa != NULL) {
2058
            /* Clear any other pendingPeer */
2059
            XFREE(ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->heap,
2060
                  DYNAMIC_TYPE_SOCKADDR);
2061
            ssl->buffers.dtlsCtx.pendingPeer.sa = NULL;
2062
            ssl->buffers.dtlsCtx.pendingPeer.sz = 0;
2063
            ssl->buffers.dtlsCtx.pendingPeer.bufSz = 0;
2064
        }
2065
        ret = WOLFSSL_SUCCESS;
2066
    }
2067
    else {
2068
        ret = SockAddrSet(&ssl->buffers.dtlsCtx.pendingPeer, peer, peerSz,
2069
                ssl->heap);
2070
    }
2071
    if (ret == WOLFSSL_SUCCESS)
2072
        ssl->buffers.dtlsCtx.processingPendingRecord = 0;
2073
#ifdef WOLFSSL_RW_THREADED
2074
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
2075
        ret = WOLFSSL_FAILURE;
2076
#endif
2077
    return ret;
2078
#else
2079
    (void)ssl;
2080
    (void)peer;
2081
    (void)peerSz;
2082
    return WOLFSSL_NOT_IMPLEMENTED;
2083
#endif
2084
}
2085
#endif /* WOLFSSL_DTLS_CID && !WOLFSSL_NO_SOCK */
2086
2087
int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz)
2088
0
{
2089
#ifdef WOLFSSL_DTLS
2090
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
2091
    if (ssl == NULL)
2092
        return WOLFSSL_FAILURE;
2093
#ifdef WOLFSSL_RW_THREADED
2094
    if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0)
2095
        return WOLFSSL_FAILURE;
2096
#endif
2097
    if (peer != NULL && peerSz != NULL
2098
            && *peerSz >= ssl->buffers.dtlsCtx.peer.sz
2099
            && ssl->buffers.dtlsCtx.peer.sa != NULL) {
2100
        *peerSz = ssl->buffers.dtlsCtx.peer.sz;
2101
        XMEMCPY(peer, ssl->buffers.dtlsCtx.peer.sa, *peerSz);
2102
        ret = WOLFSSL_SUCCESS;
2103
    }
2104
#ifdef WOLFSSL_RW_THREADED
2105
    if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0)
2106
        ret = WOLFSSL_FAILURE;
2107
#endif
2108
    return ret;
2109
#else
2110
0
    (void)ssl;
2111
0
    (void)peer;
2112
0
    (void)peerSz;
2113
0
    return WOLFSSL_NOT_IMPLEMENTED;
2114
0
#endif
2115
0
}
2116
2117
int wolfSSL_dtls_get0_peer(WOLFSSL* ssl, const void** peer,
2118
                           unsigned int* peerSz)
2119
0
{
2120
#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_RW_THREADED)
2121
    if (ssl == NULL)
2122
        return WOLFSSL_FAILURE;
2123
2124
    if (peer == NULL || peerSz == NULL)
2125
        return WOLFSSL_FAILURE;
2126
2127
    *peer = ssl->buffers.dtlsCtx.peer.sa;
2128
    *peerSz = ssl->buffers.dtlsCtx.peer.sz;
2129
    return WOLFSSL_SUCCESS;
2130
#else
2131
0
    (void)ssl;
2132
0
    (void)peer;
2133
0
    (void)peerSz;
2134
0
    return WOLFSSL_NOT_IMPLEMENTED;
2135
0
#endif
2136
0
}
2137
2138
2139
#if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS)
2140
2141
int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx)
2142
{
2143
    WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_sctp");
2144
2145
    if (ctx == NULL)
2146
        return BAD_FUNC_ARG;
2147
2148
    ctx->dtlsSctp = 1;
2149
    return WOLFSSL_SUCCESS;
2150
}
2151
2152
2153
int wolfSSL_dtls_set_sctp(WOLFSSL* ssl)
2154
{
2155
    WOLFSSL_ENTER("wolfSSL_dtls_set_sctp");
2156
2157
    if (ssl == NULL)
2158
        return BAD_FUNC_ARG;
2159
2160
    ssl->options.dtlsSctp = 1;
2161
    return WOLFSSL_SUCCESS;
2162
}
2163
2164
#endif /* WOLFSSL_DTLS && WOLFSSL_SCTP */
2165
2166
#if (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)) && \
2167
                                                           defined(WOLFSSL_DTLS)
2168
2169
int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, word16 newMtu)
2170
{
2171
    if (ctx == NULL || newMtu > MAX_RECORD_SIZE)
2172
        return BAD_FUNC_ARG;
2173
2174
    ctx->dtlsMtuSz = newMtu;
2175
    return WOLFSSL_SUCCESS;
2176
}
2177
2178
2179
int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu)
2180
{
2181
    if (ssl == NULL)
2182
        return BAD_FUNC_ARG;
2183
2184
    if (newMtu > MAX_RECORD_SIZE) {
2185
        ssl->error = BAD_FUNC_ARG;
2186
        return WOLFSSL_FAILURE;
2187
    }
2188
2189
    ssl->dtlsMtuSz = newMtu;
2190
    return WOLFSSL_SUCCESS;
2191
}
2192
2193
#ifdef OPENSSL_EXTRA
2194
/* Maps to compatibility API SSL_set_mtu and is same as wolfSSL_dtls_set_mtu,
2195
 * but expects only success or failure returns. */
2196
int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu)
2197
{
2198
    if (wolfSSL_dtls_set_mtu(ssl, mtu) == WOLFSSL_SUCCESS)
2199
        return WOLFSSL_SUCCESS;
2200
    else
2201
        return WOLFSSL_FAILURE;
2202
}
2203
#endif /* OPENSSL_EXTRA */
2204
2205
#endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */
2206
2207
#ifdef WOLFSSL_SRTP
2208
2209
static const WOLFSSL_SRTP_PROTECTION_PROFILE gSrtpProfiles[] = {
2210
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 80-bits
2211
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
2212
    {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80,
2213
     (((128 + 112) * 2) / 8) },
2214
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 32-bits
2215
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
2216
    {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32,
2217
     (((128 + 112) * 2) / 8) },
2218
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 80-bits */
2219
    {"SRTP_NULL_SHA1_80", SRTP_NULL_SHA1_80, ((112 * 2) / 8)},
2220
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 32-bits */
2221
    {"SRTP_NULL_SHA1_32", SRTP_NULL_SHA1_32, ((112 * 2) / 8)},
2222
    /* AES GCM 128, Salt: 96-bits, Auth GCM Tag 128-bits
2223
     * (master_key:128bits + master_salt:96bits) * 2 = 448 bits (56) */
2224
    {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM, (((128 + 96) * 2) / 8) },
2225
    /* AES GCM 256, Salt: 96-bits, Auth GCM Tag 128-bits
2226
     * (master_key:256bits + master_salt:96bits) * 2 = 704 bits (88) */
2227
    {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM, (((256 + 96) * 2) / 8) },
2228
};
2229
2230
static const WOLFSSL_SRTP_PROTECTION_PROFILE* DtlsSrtpFindProfile(
2231
    const char* profile_str, word32 profile_str_len, unsigned long id)
2232
{
2233
    int i;
2234
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
2235
    for (i=0;
2236
         i<(int)(sizeof(gSrtpProfiles)/sizeof(WOLFSSL_SRTP_PROTECTION_PROFILE));
2237
         i++) {
2238
        if (profile_str != NULL) {
2239
            word32 srtp_profile_len = (word32)XSTRLEN(gSrtpProfiles[i].name);
2240
            if (srtp_profile_len == profile_str_len &&
2241
                XMEMCMP(gSrtpProfiles[i].name, profile_str, profile_str_len)
2242
                                                                         == 0) {
2243
                profile = &gSrtpProfiles[i];
2244
                break;
2245
            }
2246
        }
2247
        else if (id != 0 && gSrtpProfiles[i].id == id) {
2248
            profile = &gSrtpProfiles[i];
2249
            break;
2250
        }
2251
    }
2252
    return profile;
2253
}
2254
2255
/* profile_str: accepts ":" colon separated list of SRTP profiles */
2256
static int DtlsSrtpSelProfiles(word16* id, const char* profile_str)
2257
{
2258
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile;
2259
    const char *current, *next = NULL;
2260
    word32 length = 0, current_length;
2261
2262
    *id = 0; /* reset destination ID's */
2263
2264
    if (profile_str == NULL) {
2265
        return WOLFSSL_FAILURE;
2266
    }
2267
2268
    /* loop on end of line or colon ":" */
2269
    next = profile_str;
2270
    length = (word32)XSTRLEN(profile_str);
2271
    do {
2272
        current = next;
2273
        next = XSTRSTR(current, ":");
2274
        if (next) {
2275
            current_length = (word32)(next - current);
2276
            ++next; /* ++ needed to skip ':' */
2277
        } else {
2278
            current_length = (word32)XSTRLEN(current);
2279
        }
2280
        if (current_length < length)
2281
            length = current_length;
2282
        profile = DtlsSrtpFindProfile(current, current_length, 0);
2283
        if (profile != NULL) {
2284
            *id |= (1 << profile->id); /* selected bit based on ID */
2285
        }
2286
    } while (next != NULL);
2287
    return WOLFSSL_SUCCESS;
2288
}
2289
2290
/**
2291
 * @brief Set the SRTP protection profiles for DTLS.
2292
 *
2293
 * @param ctx Pointer to the WOLFSSL_CTX structure representing the SSL/TLS
2294
 *            context.
2295
 * @param profile_str A colon-separated string of SRTP profile names.
2296
 * @return 0 on success to match OpenSSL
2297
 * @return 1 on error to match OpenSSL
2298
 */
2299
int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str)
2300
{
2301
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
2302
    if (ctx != NULL) {
2303
        ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str);
2304
    }
2305
2306
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) {
2307
        ret = 1;
2308
    } else {
2309
        ret = 0;
2310
    }
2311
2312
    return ret;
2313
}
2314
2315
/**
2316
 * @brief Set the SRTP protection profiles for DTLS.
2317
 *
2318
 * @param ssl Pointer to the WOLFSSL structure representing the SSL/TLS
2319
 *            session.
2320
 * @param profile_str A colon-separated string of SRTP profile names.
2321
 * @return 0 on success to match OpenSSL
2322
 * @return 1 on error to match OpenSSL
2323
 */
2324
int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str)
2325
{
2326
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
2327
    if (ssl != NULL) {
2328
        ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str);
2329
    }
2330
2331
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) {
2332
        ret = 1;
2333
    } else {
2334
        ret = 0;
2335
    }
2336
2337
    return ret;
2338
}
2339
2340
const WOLFSSL_SRTP_PROTECTION_PROFILE* wolfSSL_get_selected_srtp_profile(
2341
    WOLFSSL* ssl)
2342
{
2343
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
2344
    if (ssl) {
2345
        profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
2346
    }
2347
    return profile;
2348
}
2349
#ifndef NO_WOLFSSL_STUB
2350
WOLF_STACK_OF(WOLFSSL_SRTP_PROTECTION_PROFILE)* wolfSSL_get_srtp_profiles(
2351
    WOLFSSL* ssl)
2352
{
2353
    /* Not yet implemented - should return list of available SRTP profiles
2354
     * ssl->dtlsSrtpProfiles */
2355
    (void)ssl;
2356
    return NULL;
2357
}
2358
#endif
2359
2360
#define DTLS_SRTP_KEYING_MATERIAL_LABEL "EXTRACTOR-dtls_srtp"
2361
2362
int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl,
2363
    unsigned char* out, size_t* olen)
2364
{
2365
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
2366
2367
    if (ssl == NULL || olen == NULL) {
2368
        return BAD_FUNC_ARG;
2369
    }
2370
2371
    profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
2372
    if (profile == NULL) {
2373
        WOLFSSL_MSG("Not using DTLS SRTP");
2374
        return EXT_MISSING;
2375
    }
2376
    if (out == NULL) {
2377
        *olen = (size_t)profile->kdfBits;
2378
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
2379
    }
2380
2381
    if (*olen < (size_t)profile->kdfBits) {
2382
        return BUFFER_E;
2383
    }
2384
2385
    return wolfSSL_export_keying_material(ssl, out, (size_t)profile->kdfBits,
2386
            DTLS_SRTP_KEYING_MATERIAL_LABEL,
2387
            XSTR_SIZEOF(DTLS_SRTP_KEYING_MATERIAL_LABEL), NULL, 0, 0);
2388
}
2389
2390
#endif /* WOLFSSL_SRTP */
2391
2392
2393
#ifdef WOLFSSL_DTLS_DROP_STATS
2394
2395
int wolfSSL_dtls_get_drop_stats(WOLFSSL* ssl,
2396
                                word32* macDropCount, word32* replayDropCount)
2397
{
2398
    int ret;
2399
2400
    WOLFSSL_ENTER("wolfSSL_dtls_get_drop_stats");
2401
2402
    if (ssl == NULL)
2403
        ret = BAD_FUNC_ARG;
2404
    else {
2405
        ret = WOLFSSL_SUCCESS;
2406
        if (macDropCount != NULL)
2407
            *macDropCount = ssl->macDropCount;
2408
        if (replayDropCount != NULL)
2409
            *replayDropCount = ssl->replayDropCount;
2410
    }
2411
2412
    WOLFSSL_LEAVE("wolfSSL_dtls_get_drop_stats", ret);
2413
    return ret;
2414
}
2415
2416
#endif /* WOLFSSL_DTLS_DROP_STATS */
2417
2418
2419
#if defined(WOLFSSL_MULTICAST)
2420
2421
int wolfSSL_CTX_mcast_set_member_id(WOLFSSL_CTX* ctx, word16 id)
2422
{
2423
    int ret = 0;
2424
2425
    WOLFSSL_ENTER("wolfSSL_CTX_mcast_set_member_id");
2426
2427
    if (ctx == NULL || id > WOLFSSL_MAX_8BIT)
2428
        ret = BAD_FUNC_ARG;
2429
2430
    if (ret == 0) {
2431
        ctx->haveEMS = 0;
2432
        ctx->haveMcast = 1;
2433
        ctx->mcastID = (byte)id;
2434
#ifndef WOLFSSL_USER_IO
2435
        ctx->CBIORecv = EmbedReceiveFromMcast;
2436
#endif /* WOLFSSL_USER_IO */
2437
2438
        ret = WOLFSSL_SUCCESS;
2439
    }
2440
    WOLFSSL_LEAVE("wolfSSL_CTX_mcast_set_member_id", ret);
2441
    return ret;
2442
}
2443
2444
int wolfSSL_mcast_get_max_peers(void)
2445
{
2446
    return WOLFSSL_MULTICAST_PEERS;
2447
}
2448
2449
#ifdef WOLFSSL_DTLS
2450
static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
2451
                                         word32 second, word32 high)
2452
{
2453
    word32 newCur = 0;
2454
2455
    if (cur < first)
2456
        newCur = first;
2457
    else if (cur < second)
2458
        newCur = second;
2459
    else if (cur < high)
2460
        newCur = high;
2461
2462
    return newCur;
2463
}
2464
#endif /* WOLFSSL_DTLS */
2465
2466
2467
int wolfSSL_set_secret(WOLFSSL* ssl, word16 epoch,
2468
                       const byte* preMasterSecret, word32 preMasterSz,
2469
                       const byte* clientRandom, const byte* serverRandom,
2470
                       const byte* suite)
2471
{
2472
    int ret = 0;
2473
2474
    WOLFSSL_ENTER("wolfSSL_set_secret");
2475
2476
    if (ssl == NULL || preMasterSecret == NULL ||
2477
        preMasterSz == 0 || preMasterSz > ENCRYPT_LEN ||
2478
        clientRandom == NULL || serverRandom == NULL || suite == NULL) {
2479
2480
        ret = BAD_FUNC_ARG;
2481
    }
2482
2483
    if (ret == 0 && ssl->arrays->preMasterSecret == NULL) {
2484
        ssl->arrays->preMasterSz = ENCRYPT_LEN;
2485
        ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
2486
            DYNAMIC_TYPE_SECRET);
2487
        if (ssl->arrays->preMasterSecret == NULL) {
2488
            ret = MEMORY_E;
2489
        }
2490
    }
2491
2492
    if (ret == 0) {
2493
        XMEMCPY(ssl->arrays->preMasterSecret, preMasterSecret, preMasterSz);
2494
        XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0,
2495
            ENCRYPT_LEN - preMasterSz);
2496
        ssl->arrays->preMasterSz = preMasterSz;
2497
        XMEMCPY(ssl->arrays->clientRandom, clientRandom, RAN_LEN);
2498
        XMEMCPY(ssl->arrays->serverRandom, serverRandom, RAN_LEN);
2499
        ssl->options.cipherSuite0 = suite[0];
2500
        ssl->options.cipherSuite = suite[1];
2501
2502
        ret = SetCipherSpecs(ssl);
2503
    }
2504
2505
    if (ret == 0)
2506
        ret = MakeTlsMasterSecret(ssl);
2507
2508
    if (ret == 0) {
2509
        ssl->keys.encryptionOn = 1;
2510
        ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
2511
    }
2512
2513
    if (ret == 0) {
2514
        if (ssl->options.dtls) {
2515
        #ifdef WOLFSSL_DTLS
2516
            WOLFSSL_DTLS_PEERSEQ* peerSeq;
2517
            int i;
2518
2519
            ssl->keys.dtls_epoch = epoch;
2520
            for (i = 0, peerSeq = ssl->keys.peerSeq;
2521
                 i < WOLFSSL_DTLS_PEERSEQ_SZ;
2522
                 i++, peerSeq++) {
2523
2524
                peerSeq->nextEpoch = epoch;
2525
                peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
2526
                peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
2527
                peerSeq->nextSeq_lo = 0;
2528
                peerSeq->nextSeq_hi = 0;
2529
                XMEMCPY(peerSeq->prevWindow, peerSeq->window, DTLS_SEQ_SZ);
2530
                XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
2531
                peerSeq->highwaterMark = UpdateHighwaterMark(0,
2532
                        ssl->ctx->mcastFirstSeq,
2533
                        ssl->ctx->mcastSecondSeq,
2534
                        ssl->ctx->mcastMaxSeq);
2535
            }
2536
        #else
2537
            (void)epoch;
2538
        #endif
2539
        }
2540
        FreeHandshakeResources(ssl);
2541
        ret = WOLFSSL_SUCCESS;
2542
    }
2543
    else {
2544
        if (ssl)
2545
            ssl->error = ret;
2546
        ret = WOLFSSL_FATAL_ERROR;
2547
    }
2548
    WOLFSSL_LEAVE("wolfSSL_set_secret", ret);
2549
    return ret;
2550
}
2551
2552
2553
#ifdef WOLFSSL_DTLS
2554
2555
int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub)
2556
{
2557
    WOLFSSL_DTLS_PEERSEQ* p = NULL;
2558
    int ret = WOLFSSL_SUCCESS;
2559
    int i;
2560
2561
    WOLFSSL_ENTER("wolfSSL_mcast_peer_add");
2562
    if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT)
2563
        return BAD_FUNC_ARG;
2564
2565
    if (!sub) {
2566
        /* Make sure it isn't already present, while keeping the first
2567
         * open spot. */
2568
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
2569
            if (ssl->keys.peerSeq[i].peerId == INVALID_PEER_ID)
2570
                p = &ssl->keys.peerSeq[i];
2571
            if (ssl->keys.peerSeq[i].peerId == peerId) {
2572
                WOLFSSL_MSG("Peer ID already in multicast peer list.");
2573
                p = NULL;
2574
            }
2575
        }
2576
2577
        if (p != NULL) {
2578
            XMEMSET(p, 0, sizeof(WOLFSSL_DTLS_PEERSEQ));
2579
            p->peerId = peerId;
2580
            p->highwaterMark = UpdateHighwaterMark(0,
2581
                ssl->ctx->mcastFirstSeq,
2582
                ssl->ctx->mcastSecondSeq,
2583
                ssl->ctx->mcastMaxSeq);
2584
        }
2585
        else {
2586
            WOLFSSL_MSG("No room in peer list.");
2587
            ret = WOLFSSL_FATAL_ERROR;
2588
        }
2589
    }
2590
    else {
2591
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
2592
            if (ssl->keys.peerSeq[i].peerId == peerId)
2593
                p = &ssl->keys.peerSeq[i];
2594
        }
2595
2596
        if (p != NULL) {
2597
            p->peerId = INVALID_PEER_ID;
2598
        }
2599
        else {
2600
            WOLFSSL_MSG("Peer not found in list.");
2601
        }
2602
    }
2603
2604
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_add", ret);
2605
    return ret;
2606
}
2607
2608
2609
/* If peerId is in the list of peers and its last sequence number is non-zero,
2610
 * return 1, otherwise return 0. */
2611
int wolfSSL_mcast_peer_known(WOLFSSL* ssl, unsigned short peerId)
2612
{
2613
    int known = 0;
2614
    int i;
2615
2616
    WOLFSSL_ENTER("wolfSSL_mcast_peer_known");
2617
2618
    if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT) {
2619
        return BAD_FUNC_ARG;
2620
    }
2621
2622
    for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
2623
        if (ssl->keys.peerSeq[i].peerId == peerId) {
2624
            if (ssl->keys.peerSeq[i].nextSeq_hi ||
2625
                ssl->keys.peerSeq[i].nextSeq_lo) {
2626
2627
                known = 1;
2628
            }
2629
            break;
2630
        }
2631
    }
2632
2633
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_known", known);
2634
    return known;
2635
}
2636
2637
2638
int wolfSSL_CTX_mcast_set_highwater_cb(WOLFSSL_CTX* ctx, word32 maxSeq,
2639
                                       word32 first, word32 second,
2640
                                       CallbackMcastHighwater cb)
2641
{
2642
    if (ctx == NULL || (second && first > second) ||
2643
        first > maxSeq || second > maxSeq || cb == NULL) {
2644
2645
        return BAD_FUNC_ARG;
2646
    }
2647
2648
    ctx->mcastHwCb = cb;
2649
    ctx->mcastFirstSeq = first;
2650
    ctx->mcastSecondSeq = second;
2651
    ctx->mcastMaxSeq = maxSeq;
2652
2653
    return WOLFSSL_SUCCESS;
2654
}
2655
2656
2657
int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx)
2658
{
2659
    if (ssl == NULL || ctx == NULL)
2660
        return BAD_FUNC_ARG;
2661
2662
    ssl->mcastHwCbCtx = ctx;
2663
2664
    return WOLFSSL_SUCCESS;
2665
}
2666
2667
#endif /* WOLFSSL_DTLS */
2668
2669
#endif /* WOLFSSL_MULTICAST */
2670
2671
2672
#endif /* WOLFSSL_LEANPSK */
2673
2674
#ifndef NO_TLS
2675
/* return underlying connect or accept, WOLFSSL_SUCCESS on ok */
2676
int wolfSSL_negotiate(WOLFSSL* ssl)
2677
235
{
2678
235
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
2679
2680
235
    WOLFSSL_ENTER("wolfSSL_negotiate");
2681
2682
235
    if (ssl == NULL)
2683
0
        return WOLFSSL_FATAL_ERROR;
2684
2685
235
#ifndef NO_WOLFSSL_SERVER
2686
235
    if (ssl->options.side == WOLFSSL_SERVER_END) {
2687
235
#ifdef WOLFSSL_TLS13
2688
235
        if (IsAtLeastTLSv1_3(ssl->version))
2689
235
            err = wolfSSL_accept_TLSv13(ssl);
2690
0
        else
2691
0
#endif
2692
0
            err = wolfSSL_accept(ssl);
2693
235
    }
2694
235
#endif
2695
2696
235
#ifndef NO_WOLFSSL_CLIENT
2697
235
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
2698
0
#ifdef WOLFSSL_TLS13
2699
0
        if (IsAtLeastTLSv1_3(ssl->version))
2700
0
            err = wolfSSL_connect_TLSv13(ssl);
2701
0
        else
2702
0
#endif
2703
0
            err = wolfSSL_connect(ssl);
2704
0
    }
2705
235
#endif
2706
2707
235
    (void)ssl;
2708
2709
235
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
2710
2711
235
    return err;
2712
235
}
2713
#endif /* !NO_TLS */
2714
2715
WOLFSSL_ABI
2716
WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
2717
0
{
2718
0
    if (ssl) {
2719
0
        return ssl->rng;
2720
0
    }
2721
2722
0
    return NULL;
2723
0
}
2724
2725
2726
#ifndef WOLFSSL_LEANPSK
2727
/* object size based on build */
2728
int wolfSSL_GetObjectSize(void)
2729
0
{
2730
#ifdef SHOW_SIZES
2731
    printf("sizeof suites           = %lu\n", (unsigned long)sizeof(Suites));
2732
    printf("sizeof ciphers(2)       = %lu\n", (unsigned long)sizeof(Ciphers));
2733
#ifndef NO_RC4
2734
    printf("\tsizeof arc4         = %lu\n", (unsigned long)sizeof(Arc4));
2735
#endif
2736
    printf("\tsizeof aes          = %lu\n", (unsigned long)sizeof(Aes));
2737
#ifndef NO_DES3
2738
    printf("\tsizeof des3         = %lu\n", (unsigned long)sizeof(Des3));
2739
#endif
2740
#ifdef HAVE_CHACHA
2741
    printf("\tsizeof chacha       = %lu\n", (unsigned long)sizeof(ChaCha));
2742
#endif
2743
#ifdef WOLFSSL_SM4
2744
    printf("\tsizeof sm4          = %lu\n", (unsigned long)sizeof(Sm4));
2745
#endif
2746
    printf("sizeof cipher specs     = %lu\n", (unsigned long)
2747
        sizeof(CipherSpecs));
2748
    printf("sizeof keys             = %lu\n", (unsigned long)sizeof(Keys));
2749
    printf("sizeof Hashes(2)        = %lu\n", (unsigned long)sizeof(Hashes));
2750
#ifndef NO_MD5
2751
    printf("\tsizeof MD5          = %lu\n", (unsigned long)sizeof(wc_Md5));
2752
#endif
2753
#ifndef NO_SHA
2754
    printf("\tsizeof SHA          = %lu\n", (unsigned long)sizeof(wc_Sha));
2755
#endif
2756
#ifdef WOLFSSL_SHA224
2757
    printf("\tsizeof SHA224       = %lu\n", (unsigned long)sizeof(wc_Sha224));
2758
#endif
2759
#ifndef NO_SHA256
2760
    printf("\tsizeof SHA256       = %lu\n", (unsigned long)sizeof(wc_Sha256));
2761
#endif
2762
#ifdef WOLFSSL_SHA384
2763
    printf("\tsizeof SHA384       = %lu\n", (unsigned long)sizeof(wc_Sha384));
2764
#endif
2765
#ifdef WOLFSSL_SHA384
2766
    printf("\tsizeof SHA512       = %lu\n", (unsigned long)sizeof(wc_Sha512));
2767
#endif
2768
#ifdef WOLFSSL_SM3
2769
    printf("\tsizeof sm3          = %lu\n", (unsigned long)sizeof(Sm3));
2770
#endif
2771
    printf("sizeof Buffers          = %lu\n", (unsigned long)sizeof(Buffers));
2772
    printf("sizeof Options          = %lu\n", (unsigned long)sizeof(Options));
2773
    printf("sizeof Arrays           = %lu\n", (unsigned long)sizeof(Arrays));
2774
#ifndef NO_RSA
2775
    printf("sizeof RsaKey           = %lu\n", (unsigned long)sizeof(RsaKey));
2776
#endif
2777
#ifdef HAVE_ECC
2778
    printf("sizeof ecc_key          = %lu\n", (unsigned long)sizeof(ecc_key));
2779
#endif
2780
    printf("sizeof WOLFSSL_CIPHER    = %lu\n", (unsigned long)
2781
        sizeof(WOLFSSL_CIPHER));
2782
    printf("sizeof WOLFSSL_SESSION   = %lu\n", (unsigned long)
2783
        sizeof(WOLFSSL_SESSION));
2784
    printf("sizeof WOLFSSL           = %lu\n", (unsigned long)sizeof(WOLFSSL));
2785
    printf("sizeof WOLFSSL_CTX       = %lu\n", (unsigned long)
2786
        sizeof(WOLFSSL_CTX));
2787
#endif
2788
2789
0
    return sizeof(WOLFSSL);
2790
0
}
2791
2792
int wolfSSL_CTX_GetObjectSize(void)
2793
0
{
2794
0
    return sizeof(WOLFSSL_CTX);
2795
0
}
2796
2797
int wolfSSL_METHOD_GetObjectSize(void)
2798
0
{
2799
0
    return sizeof(WOLFSSL_METHOD);
2800
0
}
2801
#endif
2802
2803
2804
#ifdef WOLFSSL_STATIC_MEMORY
2805
2806
int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx,
2807
    wolfSSL_method_func method, unsigned char* buf, unsigned int sz, int flag,
2808
    int maxSz)
2809
{
2810
    WOLFSSL_HEAP_HINT* hint = NULL;
2811
2812
    if (ctx == NULL || buf == NULL) {
2813
        return BAD_FUNC_ARG;
2814
    }
2815
2816
    if (*ctx == NULL && method == NULL) {
2817
        return BAD_FUNC_ARG;
2818
    }
2819
2820
    /* If there is a heap already, capture it in hint. */
2821
    if (*ctx && (*ctx)->heap != NULL) {
2822
        hint = (*ctx)->heap;
2823
    }
2824
2825
    if (wc_LoadStaticMemory(&hint, buf, sz, flag, maxSz)) {
2826
        WOLFSSL_MSG("Error loading static memory");
2827
        return WOLFSSL_FAILURE;
2828
    }
2829
2830
    if (*ctx) {
2831
        if ((*ctx)->heap == NULL) {
2832
            (*ctx)->heap = (void*)hint;
2833
        }
2834
    }
2835
    else {
2836
        /* create ctx if needed */
2837
        *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
2838
        if (*ctx == NULL) {
2839
            WOLFSSL_MSG("Error creating ctx");
2840
            return WOLFSSL_FAILURE;
2841
        }
2842
    }
2843
2844
    return WOLFSSL_SUCCESS;
2845
}
2846
2847
2848
int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
2849
{
2850
    if (ssl == NULL) {
2851
        return BAD_FUNC_ARG;
2852
    }
2853
    WOLFSSL_ENTER("wolfSSL_is_static_memory");
2854
2855
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
2856
    /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
2857
    if (mem_stats != NULL && ssl->heap != NULL) {
2858
        WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
2859
        WOLFSSL_HEAP* heap      = hint->memory;
2860
        if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
2861
            XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
2862
        }
2863
    }
2864
#endif
2865
2866
    (void)mem_stats;
2867
    return (ssl->heap) ? 1 : 0;
2868
}
2869
2870
2871
int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
2872
{
2873
    if (ctx == NULL) {
2874
        return BAD_FUNC_ARG;
2875
    }
2876
    WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
2877
2878
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
2879
    /* fill out statistics if wanted */
2880
    if (mem_stats != NULL && ctx->heap != NULL) {
2881
        WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
2882
        if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
2883
            return MEMORY_E;
2884
        }
2885
    }
2886
#endif
2887
2888
    (void)mem_stats;
2889
    return (ctx->heap) ? 1 : 0;
2890
}
2891
2892
#endif /* WOLFSSL_STATIC_MEMORY */
2893
2894
#ifndef NO_TLS
2895
/* return max record layer size plaintext input size */
2896
int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
2897
0
{
2898
0
    WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
2899
2900
0
    if (ssl == NULL)
2901
0
        return BAD_FUNC_ARG;
2902
2903
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE) {
2904
0
        WOLFSSL_MSG("Handshake not complete yet");
2905
0
        return BAD_FUNC_ARG;
2906
0
    }
2907
2908
0
    return min(OUTPUT_RECORD_SIZE, wolfssl_local_GetMaxPlaintextSize(ssl));
2909
0
}
2910
2911
2912
/* return record layer size of plaintext input size */
2913
int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
2914
0
{
2915
0
    int maxSize;
2916
2917
0
    WOLFSSL_ENTER("wolfSSL_GetOutputSize");
2918
2919
0
    if (inSz < 0)
2920
0
        return BAD_FUNC_ARG;
2921
2922
0
    maxSize = wolfSSL_GetMaxOutputSize(ssl);
2923
0
    if (maxSize < 0)
2924
0
        return maxSize;   /* error */
2925
0
    if (inSz > maxSize)
2926
0
        return INPUT_SIZE_E;
2927
2928
0
    return wolfssl_local_GetRecordSize(ssl, inSz, 1);
2929
0
}
2930
2931
2932
#ifdef HAVE_ECC
2933
int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2934
0
{
2935
0
    short keySzBytes;
2936
2937
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinEccKey_Sz");
2938
0
    if (ctx == NULL || keySz < 0) {
2939
0
        WOLFSSL_MSG("Key size must be positive value or ctx was null");
2940
0
        return BAD_FUNC_ARG;
2941
0
    }
2942
2943
0
    if (keySz % 8 == 0) {
2944
0
        keySzBytes = keySz / 8;
2945
0
    }
2946
0
    else {
2947
0
        keySzBytes = (keySz / 8) + 1;
2948
0
    }
2949
2950
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2951
    if (crypto_policy.enabled) {
2952
        if (ctx->minEccKeySz > (keySzBytes)) {
2953
            return CRYPTO_POLICY_FORBIDDEN;
2954
        }
2955
    }
2956
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2957
2958
0
    ctx->minEccKeySz     = keySzBytes;
2959
0
#ifndef NO_CERTS
2960
0
    ctx->cm->minEccKeySz = keySzBytes;
2961
0
#endif
2962
0
    return WOLFSSL_SUCCESS;
2963
0
}
2964
2965
2966
int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz)
2967
0
{
2968
0
    short keySzBytes;
2969
2970
0
    WOLFSSL_ENTER("wolfSSL_SetMinEccKey_Sz");
2971
0
    if (ssl == NULL || keySz < 0) {
2972
0
        WOLFSSL_MSG("Key size must be positive value or ctx was null");
2973
0
        return BAD_FUNC_ARG;
2974
0
    }
2975
2976
0
    if (keySz % 8 == 0) {
2977
0
        keySzBytes = keySz / 8;
2978
0
    }
2979
0
    else {
2980
0
        keySzBytes = (keySz / 8) + 1;
2981
0
    }
2982
2983
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2984
    if (crypto_policy.enabled) {
2985
        if (ssl->options.minEccKeySz > (keySzBytes)) {
2986
            return CRYPTO_POLICY_FORBIDDEN;
2987
        }
2988
    }
2989
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2990
2991
0
    ssl->options.minEccKeySz = keySzBytes;
2992
0
    return WOLFSSL_SUCCESS;
2993
0
}
2994
2995
#endif /* HAVE_ECC */
2996
2997
#ifndef NO_RSA
2998
int wolfSSL_CTX_SetMinRsaKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2999
0
{
3000
0
    if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
3001
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
3002
0
        return BAD_FUNC_ARG;
3003
0
    }
3004
3005
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3006
    if (crypto_policy.enabled) {
3007
        if (ctx->minRsaKeySz > (keySz / 8)) {
3008
            return CRYPTO_POLICY_FORBIDDEN;
3009
        }
3010
    }
3011
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3012
3013
0
    ctx->minRsaKeySz     = keySz / 8;
3014
0
    ctx->cm->minRsaKeySz = keySz / 8;
3015
0
    return WOLFSSL_SUCCESS;
3016
0
}
3017
3018
3019
int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz)
3020
0
{
3021
0
    if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
3022
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
3023
0
        return BAD_FUNC_ARG;
3024
0
    }
3025
3026
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3027
    if (crypto_policy.enabled) {
3028
        if (ssl->options.minRsaKeySz > (keySz / 8)) {
3029
            return CRYPTO_POLICY_FORBIDDEN;
3030
        }
3031
    }
3032
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3033
3034
0
    ssl->options.minRsaKeySz = keySz / 8;
3035
0
    return WOLFSSL_SUCCESS;
3036
0
}
3037
#endif /* !NO_RSA */
3038
3039
#ifndef NO_DH
3040
3041
#if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
3042
    !defined(HAVE_SELFTEST)
3043
/* Enables or disables the session's DH key prime test. */
3044
int wolfSSL_SetEnableDhKeyTest(WOLFSSL* ssl, int enable)
3045
0
{
3046
0
    WOLFSSL_ENTER("wolfSSL_SetEnableDhKeyTest");
3047
3048
0
    if (ssl == NULL)
3049
0
        return BAD_FUNC_ARG;
3050
3051
0
    if (!enable)
3052
0
        ssl->options.dhDoKeyTest = 0;
3053
0
    else
3054
0
        ssl->options.dhDoKeyTest = 1;
3055
3056
0
    WOLFSSL_LEAVE("wolfSSL_SetEnableDhKeyTest", WOLFSSL_SUCCESS);
3057
0
    return WOLFSSL_SUCCESS;
3058
0
}
3059
#endif
3060
3061
int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
3062
0
{
3063
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
3064
0
        return BAD_FUNC_ARG;
3065
3066
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3067
    if (crypto_policy.enabled) {
3068
        if (ctx->minDhKeySz > (keySz_bits / 8)) {
3069
            return CRYPTO_POLICY_FORBIDDEN;
3070
        }
3071
    }
3072
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3073
3074
0
    ctx->minDhKeySz = keySz_bits / 8;
3075
0
    return WOLFSSL_SUCCESS;
3076
0
}
3077
3078
3079
int wolfSSL_SetMinDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
3080
0
{
3081
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
3082
0
        return BAD_FUNC_ARG;
3083
3084
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3085
    if (crypto_policy.enabled) {
3086
        if (ssl->options.minDhKeySz > (keySz_bits / 8)) {
3087
            return CRYPTO_POLICY_FORBIDDEN;
3088
        }
3089
    }
3090
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3091
3092
0
    ssl->options.minDhKeySz = keySz_bits / 8;
3093
0
    return WOLFSSL_SUCCESS;
3094
0
}
3095
3096
3097
int wolfSSL_CTX_SetMaxDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
3098
0
{
3099
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
3100
0
        return BAD_FUNC_ARG;
3101
3102
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3103
    if (crypto_policy.enabled) {
3104
        if (ctx->minDhKeySz > (keySz_bits / 8)) {
3105
            return CRYPTO_POLICY_FORBIDDEN;
3106
        }
3107
    }
3108
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3109
3110
0
    ctx->maxDhKeySz = keySz_bits / 8;
3111
0
    return WOLFSSL_SUCCESS;
3112
0
}
3113
3114
3115
int wolfSSL_SetMaxDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
3116
0
{
3117
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
3118
0
        return BAD_FUNC_ARG;
3119
3120
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3121
    if (crypto_policy.enabled) {
3122
        if (ssl->options.minDhKeySz > (keySz_bits / 8)) {
3123
            return CRYPTO_POLICY_FORBIDDEN;
3124
        }
3125
    }
3126
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3127
3128
0
    ssl->options.maxDhKeySz = keySz_bits / 8;
3129
0
    return WOLFSSL_SUCCESS;
3130
0
}
3131
3132
3133
int wolfSSL_GetDhKey_Sz(WOLFSSL* ssl)
3134
0
{
3135
0
    if (ssl == NULL)
3136
0
        return BAD_FUNC_ARG;
3137
3138
0
    return (ssl->options.dhKeySz * 8);
3139
0
}
3140
3141
#endif /* !NO_DH */
3142
3143
3144
static int wolfSSL_write_internal(WOLFSSL* ssl, const void* data, size_t sz)
3145
{
3146
    int ret;
3147
3148
    WOLFSSL_ENTER("wolfSSL_write");
3149
3150
    if (ssl == NULL || data == NULL)
3151
        return BAD_FUNC_ARG;
3152
3153
#ifdef WOLFSSL_QUIC
3154
    if (WOLFSSL_IS_QUIC(ssl)) {
3155
        WOLFSSL_MSG("SSL_write() on QUIC not allowed");
3156
        return BAD_FUNC_ARG;
3157
    }
3158
#endif
3159
3160
#ifdef HAVE_WRITE_DUP
3161
    { /* local variable scope */
3162
        int dupErr = 0;   /* local copy */
3163
3164
        ret = 0;
3165
3166
        if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
3167
            WOLFSSL_MSG("Read dup side cannot write");
3168
            return WRITE_DUP_WRITE_E;
3169
        }
3170
        if (ssl->dupWrite) {
3171
            if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0) {
3172
                return BAD_MUTEX_E;
3173
            }
3174
            dupErr = ssl->dupWrite->dupErr;
3175
            ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
3176
        }
3177
3178
        if (ret != 0) {
3179
            ssl->error = ret;  /* high priority fatal error */
3180
            return WOLFSSL_FATAL_ERROR;
3181
        }
3182
        if (dupErr != 0) {
3183
            WOLFSSL_MSG("Write dup error from other side");
3184
            ssl->error = dupErr;
3185
            return WOLFSSL_FATAL_ERROR;
3186
        }
3187
    }
3188
#endif
3189
3190
#ifdef HAVE_ERRNO_H
3191
    errno = 0;
3192
#endif
3193
3194
    #ifdef OPENSSL_EXTRA
3195
    if (ssl->CBIS != NULL) {
3196
        ssl->CBIS(ssl, WOLFSSL_CB_WRITE, WOLFSSL_SUCCESS);
3197
        ssl->cbmode = WOLFSSL_CB_WRITE;
3198
    }
3199
    #endif
3200
    ret = SendData(ssl, data, sz);
3201
3202
    WOLFSSL_LEAVE("wolfSSL_write", ret);
3203
3204
    if (ret < 0)
3205
        return WOLFSSL_FATAL_ERROR;
3206
    else
3207
        return ret;
3208
}
3209
3210
WOLFSSL_ABI
3211
int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
3212
235
{
3213
235
    WOLFSSL_ENTER("wolfSSL_write");
3214
3215
235
    if (sz < 0)
3216
0
        return BAD_FUNC_ARG;
3217
3218
235
    return wolfSSL_write_internal(ssl, data, (size_t)sz);
3219
235
}
3220
3221
int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz)
3222
0
{
3223
0
    int maxLength;
3224
0
    int usedLength;
3225
3226
0
    WOLFSSL_ENTER("wolfSSL_inject");
3227
3228
0
    if (ssl == NULL || data == NULL || sz <= 0)
3229
0
        return BAD_FUNC_ARG;
3230
3231
0
    usedLength = (int)(ssl->buffers.inputBuffer.length -
3232
0
                       ssl->buffers.inputBuffer.idx);
3233
0
    maxLength  = (int)(ssl->buffers.inputBuffer.bufferSize -
3234
0
                       (word32)usedLength);
3235
3236
0
    if (sz > maxLength) {
3237
        /* Need to make space */
3238
0
        int ret;
3239
0
        if (ssl->buffers.clearOutputBuffer.length > 0) {
3240
            /* clearOutputBuffer points into so reallocating inputBuffer will
3241
             * invalidate clearOutputBuffer and lose app data */
3242
0
            WOLFSSL_MSG("Can't inject while there is application data to read");
3243
0
            return APP_DATA_READY;
3244
0
        }
3245
0
        ret = GrowInputBuffer(ssl, sz, usedLength);
3246
0
        if (ret < 0)
3247
0
            return ret;
3248
0
    }
3249
3250
0
    XMEMCPY(ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
3251
0
            data, sz);
3252
0
    ssl->buffers.inputBuffer.length += sz;
3253
3254
0
    return WOLFSSL_SUCCESS;
3255
0
}
3256
3257
3258
int wolfSSL_write_ex(WOLFSSL* ssl, const void* data, size_t sz, size_t* wr)
3259
0
{
3260
0
    int ret;
3261
3262
0
    if (wr != NULL) {
3263
0
        *wr = 0;
3264
0
    }
3265
3266
0
    ret = wolfSSL_write_internal(ssl, data, sz);
3267
0
    if (ret >= 0) {
3268
0
        if (wr != NULL) {
3269
0
            *wr = (size_t)ret;
3270
0
        }
3271
3272
        /* handle partial write cases, if not set then a partial write is
3273
         * considered a failure case, or if set and ret is 0 then is a fail */
3274
0
        if (ret == 0 && ssl->options.partialWrite) {
3275
0
            ret = 0;
3276
0
        }
3277
0
        else if ((size_t)ret < sz && !ssl->options.partialWrite) {
3278
0
            ret = 0;
3279
0
        }
3280
0
        else {
3281
            /* wrote out all application data, or wrote out 1 byte or more with
3282
             * partial write flag set */
3283
0
            ret = 1;
3284
0
        }
3285
0
    }
3286
0
    else {
3287
0
        ret = 0;
3288
0
    }
3289
3290
0
    return ret;
3291
0
}
3292
3293
3294
static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, size_t sz, int peek)
3295
{
3296
    int ret;
3297
3298
    WOLFSSL_ENTER("wolfSSL_read_internal");
3299
3300
    if (ssl == NULL || data == NULL)
3301
        return BAD_FUNC_ARG;
3302
3303
#ifdef WOLFSSL_QUIC
3304
    if (WOLFSSL_IS_QUIC(ssl)) {
3305
        WOLFSSL_MSG("SSL_read() on QUIC not allowed");
3306
        return BAD_FUNC_ARG;
3307
    }
3308
#endif
3309
#if defined(WOLFSSL_ERROR_CODE_OPENSSL) && defined(OPENSSL_EXTRA)
3310
    /* This additional logic is meant to simulate following openSSL behavior:
3311
     * After bidirectional SSL_shutdown complete, SSL_read returns 0 and
3312
     * SSL_get_error_code returns SSL_ERROR_ZERO_RETURN.
3313
     * This behavior is used to know the disconnect of the underlying
3314
     * transport layer.
3315
     *
3316
     * In this logic, CBIORecv is called with a read size of 0 to check the
3317
     * transport layer status. It also returns WOLFSSL_FAILURE so that
3318
     * SSL_read does not return a positive number on failure.
3319
     */
3320
3321
    /* make sure bidirectional TLS shutdown completes */
3322
    if (ssl->error == WOLFSSL_ERROR_SYSCALL || ssl->options.shutdownDone) {
3323
        /* ask the underlying transport the connection is closed */
3324
        if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx)
3325
            == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE))
3326
        {
3327
            ssl->options.isClosed = 1;
3328
            ssl->error = WOLFSSL_ERROR_ZERO_RETURN;
3329
        }
3330
        return WOLFSSL_FAILURE;
3331
    }
3332
#endif
3333
3334
#ifdef HAVE_WRITE_DUP
3335
    if (ssl->dupWrite && ssl->dupSide == WRITE_DUP_SIDE) {
3336
        WOLFSSL_MSG("Write dup side cannot read");
3337
        return WRITE_DUP_READ_E;
3338
    }
3339
#endif
3340
3341
#ifdef HAVE_ERRNO_H
3342
        errno = 0;
3343
#endif
3344
3345
    ret = ReceiveData(ssl, (byte*)data, sz, peek);
3346
3347
#ifdef HAVE_WRITE_DUP
3348
    if (ssl->dupWrite) {
3349
        if (ssl->error != 0 && ssl->error != WC_NO_ERR_TRACE(WANT_READ)
3350
        #ifdef WOLFSSL_ASYNC_CRYPT
3351
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
3352
        #endif
3353
        ) {
3354
            int notifyErr;
3355
3356
            WOLFSSL_MSG("Notifying write side of fatal read error");
3357
            notifyErr  = NotifyWriteSide(ssl, ssl->error);
3358
            if (notifyErr < 0) {
3359
                ret = ssl->error = notifyErr;
3360
            }
3361
        }
3362
    }
3363
#endif
3364
3365
    WOLFSSL_LEAVE("wolfSSL_read_internal", ret);
3366
3367
    if (ret < 0)
3368
        return WOLFSSL_FATAL_ERROR;
3369
    else
3370
        return ret;
3371
}
3372
3373
3374
int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz)
3375
0
{
3376
0
    WOLFSSL_ENTER("wolfSSL_peek");
3377
3378
0
    if (sz < 0)
3379
0
        return BAD_FUNC_ARG;
3380
3381
0
    return wolfSSL_read_internal(ssl, data, (size_t)sz, TRUE);
3382
0
}
3383
3384
3385
WOLFSSL_ABI
3386
int wolfSSL_read(WOLFSSL* ssl, void* data, int sz)
3387
{
3388
    WOLFSSL_ENTER("wolfSSL_read");
3389
3390
    if (sz < 0)
3391
        return BAD_FUNC_ARG;
3392
3393
    #ifdef OPENSSL_EXTRA
3394
    if (ssl == NULL) {
3395
        return BAD_FUNC_ARG;
3396
    }
3397
    if (ssl->CBIS != NULL) {
3398
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
3399
        ssl->cbmode = WOLFSSL_CB_READ;
3400
    }
3401
    #endif
3402
    return wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
3403
}
3404
3405
3406
/* returns 0 on failure and 1 on read */
3407
int wolfSSL_read_ex(WOLFSSL* ssl, void* data, size_t sz, size_t* rd)
3408
0
{
3409
0
    int ret;
3410
3411
    #ifdef OPENSSL_EXTRA
3412
    if (ssl == NULL) {
3413
        return BAD_FUNC_ARG;
3414
    }
3415
    if (ssl->CBIS != NULL) {
3416
        ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS);
3417
        ssl->cbmode = WOLFSSL_CB_READ;
3418
    }
3419
    #endif
3420
0
    ret = wolfSSL_read_internal(ssl, data, sz, FALSE);
3421
3422
0
    if (ret > 0 && rd != NULL) {
3423
0
        *rd = (size_t)ret;
3424
0
    }
3425
3426
0
    return ret > 0 ? 1 : 0;
3427
0
}
3428
3429
#ifdef WOLFSSL_MULTICAST
3430
3431
int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz)
3432
{
3433
    int ret = 0;
3434
3435
    WOLFSSL_ENTER("wolfSSL_mcast_read");
3436
3437
    if ((ssl == NULL) || (sz < 0))
3438
        return BAD_FUNC_ARG;
3439
3440
    ret = wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE);
3441
    if (ssl->options.dtls && ssl->options.haveMcast && id != NULL)
3442
        *id = ssl->keys.curPeerId;
3443
    return ret;
3444
}
3445
3446
#endif /* WOLFSSL_MULTICAST */
3447
#endif /* !NO_TLS */
3448
3449
/* helpers to set the device id, WOLFSSL_SUCCESS on ok */
3450
WOLFSSL_ABI
3451
int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
3452
0
{
3453
0
    if (ssl == NULL)
3454
0
        return BAD_FUNC_ARG;
3455
3456
0
    ssl->devId = devId;
3457
3458
0
    return WOLFSSL_SUCCESS;
3459
0
}
3460
3461
WOLFSSL_ABI
3462
int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
3463
0
{
3464
0
    if (ctx == NULL)
3465
0
        return BAD_FUNC_ARG;
3466
3467
0
    ctx->devId = devId;
3468
3469
0
    return WOLFSSL_SUCCESS;
3470
0
}
3471
3472
/* helpers to get device id and heap */
3473
WOLFSSL_ABI
3474
int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
3475
40
{
3476
40
    int devId = INVALID_DEVID;
3477
40
    if (ssl != NULL)
3478
0
        devId = ssl->devId;
3479
40
    if (ctx != NULL && devId == INVALID_DEVID)
3480
40
        devId = ctx->devId;
3481
40
    return devId;
3482
40
}
3483
void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
3484
0
{
3485
0
    void* heap = NULL;
3486
0
    if (ctx != NULL)
3487
0
        heap = ctx->heap;
3488
0
    else if (ssl != NULL)
3489
0
        heap = ssl->heap;
3490
0
    return heap;
3491
0
}
3492
3493
3494
#ifndef NO_TLS
3495
#ifdef HAVE_SNI
3496
3497
WOLFSSL_ABI
3498
int wolfSSL_UseSNI(WOLFSSL* ssl, byte type, const void* data, word16 size)
3499
0
{
3500
0
    if (ssl == NULL)
3501
0
        return BAD_FUNC_ARG;
3502
3503
0
    return TLSX_UseSNI(&ssl->extensions, type, data, size, ssl->heap);
3504
0
}
3505
3506
3507
WOLFSSL_ABI
3508
int wolfSSL_CTX_UseSNI(WOLFSSL_CTX* ctx, byte type, const void* data,
3509
                                                                    word16 size)
3510
28
{
3511
28
    if (ctx == NULL)
3512
0
        return BAD_FUNC_ARG;
3513
3514
28
    return TLSX_UseSNI(&ctx->extensions, type, data, size, ctx->heap);
3515
28
}
3516
3517
#ifndef NO_WOLFSSL_SERVER
3518
3519
void wolfSSL_SNI_SetOptions(WOLFSSL* ssl, byte type, byte options)
3520
0
{
3521
0
    if (ssl && ssl->extensions)
3522
0
        TLSX_SNI_SetOptions(ssl->extensions, type, options);
3523
0
}
3524
3525
3526
void wolfSSL_CTX_SNI_SetOptions(WOLFSSL_CTX* ctx, byte type, byte options)
3527
0
{
3528
0
    if (ctx && ctx->extensions)
3529
0
        TLSX_SNI_SetOptions(ctx->extensions, type, options);
3530
0
}
3531
3532
3533
byte wolfSSL_SNI_Status(WOLFSSL* ssl, byte type)
3534
0
{
3535
0
    return TLSX_SNI_Status(ssl ? ssl->extensions : NULL, type);
3536
0
}
3537
3538
3539
word16 wolfSSL_SNI_GetRequest(WOLFSSL* ssl, byte type, void** data)
3540
0
{
3541
0
    if (data)
3542
0
        *data = NULL;
3543
3544
0
    if (ssl && ssl->extensions)
3545
0
        return TLSX_SNI_GetRequest(ssl->extensions, type, data, 0);
3546
3547
0
    return 0;
3548
0
}
3549
3550
3551
int wolfSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
3552
                              byte type, byte* sni, word32* inOutSz)
3553
0
{
3554
0
    if (clientHello && helloSz > 0 && sni && inOutSz && *inOutSz > 0)
3555
0
        return TLSX_SNI_GetFromBuffer(clientHello, helloSz, type, sni, inOutSz);
3556
3557
0
    return BAD_FUNC_ARG;
3558
0
}
3559
3560
#endif /* !NO_WOLFSSL_SERVER */
3561
3562
#endif /* HAVE_SNI */
3563
3564
3565
#ifdef HAVE_TRUSTED_CA
3566
3567
int wolfSSL_UseTrustedCA(WOLFSSL* ssl, byte type,
3568
    const byte* certId, word32 certIdSz)
3569
{
3570
    if (ssl == NULL)
3571
        return BAD_FUNC_ARG;
3572
3573
    if (type == WOLFSSL_TRUSTED_CA_PRE_AGREED) {
3574
        if (certId != NULL || certIdSz != 0)
3575
            return BAD_FUNC_ARG;
3576
    }
3577
    else if (type == WOLFSSL_TRUSTED_CA_X509_NAME) {
3578
        if (certId == NULL || certIdSz == 0)
3579
            return BAD_FUNC_ARG;
3580
    }
3581
    #ifndef NO_SHA
3582
    else if (type == WOLFSSL_TRUSTED_CA_KEY_SHA1 ||
3583
            type == WOLFSSL_TRUSTED_CA_CERT_SHA1) {
3584
        if (certId == NULL || certIdSz != WC_SHA_DIGEST_SIZE)
3585
            return BAD_FUNC_ARG;
3586
    }
3587
    #endif
3588
    else
3589
        return BAD_FUNC_ARG;
3590
3591
    return TLSX_UseTrustedCA(&ssl->extensions,
3592
            type, certId, certIdSz, ssl->heap);
3593
}
3594
3595
#endif /* HAVE_TRUSTED_CA */
3596
3597
3598
#ifdef HAVE_MAX_FRAGMENT
3599
#ifndef NO_WOLFSSL_CLIENT
3600
3601
int wolfSSL_UseMaxFragment(WOLFSSL* ssl, byte mfl)
3602
{
3603
    if (ssl == NULL)
3604
        return BAD_FUNC_ARG;
3605
3606
#ifdef WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST
3607
    /* The following is a non-standard way to reconfigure the max packet size
3608
        post-handshake for wolfSSL_write/wolfSSL_read */
3609
    if (ssl->options.handShakeState == HANDSHAKE_DONE) {
3610
        switch (mfl) {
3611
            case WOLFSSL_MFL_2_8 : ssl->max_fragment =  256; break;
3612
            case WOLFSSL_MFL_2_9 : ssl->max_fragment =  512; break;
3613
            case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
3614
            case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
3615
            case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
3616
            case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
3617
            default: ssl->max_fragment = MAX_RECORD_SIZE; break;
3618
        }
3619
        return WOLFSSL_SUCCESS;
3620
    }
3621
#endif /* WOLFSSL_MAX_FRAGMENT_ADJUST */
3622
3623
    /* This call sets the max fragment TLS extension, which gets sent to server.
3624
        The server_hello response is what sets the `ssl->max_fragment` in
3625
        TLSX_MFL_Parse */
3626
    return TLSX_UseMaxFragment(&ssl->extensions, mfl, ssl->heap);
3627
}
3628
3629
3630
int wolfSSL_CTX_UseMaxFragment(WOLFSSL_CTX* ctx, byte mfl)
3631
{
3632
    if (ctx == NULL)
3633
        return BAD_FUNC_ARG;
3634
3635
    return TLSX_UseMaxFragment(&ctx->extensions, mfl, ctx->heap);
3636
}
3637
3638
#endif /* NO_WOLFSSL_CLIENT */
3639
#endif /* HAVE_MAX_FRAGMENT */
3640
3641
#ifdef HAVE_TRUNCATED_HMAC
3642
#ifndef NO_WOLFSSL_CLIENT
3643
3644
int wolfSSL_UseTruncatedHMAC(WOLFSSL* ssl)
3645
{
3646
    if (ssl == NULL)
3647
        return BAD_FUNC_ARG;
3648
3649
    return TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
3650
}
3651
3652
3653
int wolfSSL_CTX_UseTruncatedHMAC(WOLFSSL_CTX* ctx)
3654
{
3655
    if (ctx == NULL)
3656
        return BAD_FUNC_ARG;
3657
3658
    return TLSX_UseTruncatedHMAC(&ctx->extensions, ctx->heap);
3659
}
3660
3661
#endif /* NO_WOLFSSL_CLIENT */
3662
#endif /* HAVE_TRUNCATED_HMAC */
3663
3664
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST
3665
3666
int wolfSSL_UseOCSPStapling(WOLFSSL* ssl, byte status_type, byte options)
3667
{
3668
    WOLFSSL_ENTER("wolfSSL_UseOCSPStapling");
3669
3670
    if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
3671
        return BAD_FUNC_ARG;
3672
3673
    return TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
3674
                                          options, NULL, ssl->heap, ssl->devId);
3675
}
3676
3677
3678
int wolfSSL_CTX_UseOCSPStapling(WOLFSSL_CTX* ctx, byte status_type,
3679
                                                                   byte options)
3680
{
3681
    WOLFSSL_ENTER("wolfSSL_CTX_UseOCSPStapling");
3682
3683
    if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
3684
        return BAD_FUNC_ARG;
3685
3686
    return TLSX_UseCertificateStatusRequest(&ctx->extensions, status_type,
3687
                                          options, NULL, ctx->heap, ctx->devId);
3688
}
3689
3690
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
3691
3692
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
3693
3694
int wolfSSL_UseOCSPStaplingV2(WOLFSSL* ssl, byte status_type, byte options)
3695
{
3696
    if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
3697
        return BAD_FUNC_ARG;
3698
3699
    return TLSX_UseCertificateStatusRequestV2(&ssl->extensions, status_type,
3700
                                                options, ssl->heap, ssl->devId);
3701
}
3702
3703
3704
int wolfSSL_CTX_UseOCSPStaplingV2(WOLFSSL_CTX* ctx, byte status_type,
3705
                                                                   byte options)
3706
{
3707
    if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
3708
        return BAD_FUNC_ARG;
3709
3710
    return TLSX_UseCertificateStatusRequestV2(&ctx->extensions, status_type,
3711
                                                options, ctx->heap, ctx->devId);
3712
}
3713
3714
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
3715
3716
/* Elliptic Curves */
3717
#if defined(HAVE_SUPPORTED_CURVES)
3718
3719
static int isValidCurveGroup(word16 name)
3720
0
{
3721
0
    switch (name) {
3722
0
        case WOLFSSL_ECC_SECP160K1:
3723
0
        case WOLFSSL_ECC_SECP160R1:
3724
0
        case WOLFSSL_ECC_SECP160R2:
3725
0
        case WOLFSSL_ECC_SECP192K1:
3726
0
        case WOLFSSL_ECC_SECP192R1:
3727
0
        case WOLFSSL_ECC_SECP224K1:
3728
0
        case WOLFSSL_ECC_SECP224R1:
3729
0
        case WOLFSSL_ECC_SECP256K1:
3730
0
        case WOLFSSL_ECC_SECP256R1:
3731
0
        case WOLFSSL_ECC_SECP384R1:
3732
0
        case WOLFSSL_ECC_SECP521R1:
3733
0
        case WOLFSSL_ECC_BRAINPOOLP256R1:
3734
0
        case WOLFSSL_ECC_BRAINPOOLP384R1:
3735
0
        case WOLFSSL_ECC_BRAINPOOLP512R1:
3736
0
        case WOLFSSL_ECC_SM2P256V1:
3737
0
        case WOLFSSL_ECC_X25519:
3738
0
        case WOLFSSL_ECC_X448:
3739
3740
0
        case WOLFSSL_FFDHE_2048:
3741
0
        case WOLFSSL_FFDHE_3072:
3742
0
        case WOLFSSL_FFDHE_4096:
3743
0
        case WOLFSSL_FFDHE_6144:
3744
0
        case WOLFSSL_FFDHE_8192:
3745
3746
#ifdef WOLFSSL_HAVE_MLKEM
3747
#ifndef WOLFSSL_NO_ML_KEM
3748
        case WOLFSSL_ML_KEM_512:
3749
        case WOLFSSL_ML_KEM_768:
3750
        case WOLFSSL_ML_KEM_1024:
3751
    #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)
3752
        case WOLFSSL_SECP256R1MLKEM512:
3753
        case WOLFSSL_SECP384R1MLKEM768:
3754
        case WOLFSSL_SECP521R1MLKEM1024:
3755
        case WOLFSSL_SECP384R1MLKEM1024:
3756
        case WOLFSSL_X25519MLKEM512:
3757
        case WOLFSSL_X448MLKEM768:
3758
        case WOLFSSL_X25519MLKEM768:
3759
        case WOLFSSL_SECP256R1MLKEM768:
3760
    #endif
3761
#endif /* !WOLFSSL_NO_ML_KEM */
3762
#ifdef WOLFSSL_MLKEM_KYBER
3763
        case WOLFSSL_KYBER_LEVEL1:
3764
        case WOLFSSL_KYBER_LEVEL3:
3765
        case WOLFSSL_KYBER_LEVEL5:
3766
    #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)
3767
        case WOLFSSL_P256_KYBER_LEVEL1:
3768
        case WOLFSSL_P384_KYBER_LEVEL3:
3769
        case WOLFSSL_P521_KYBER_LEVEL5:
3770
        case WOLFSSL_X25519_KYBER_LEVEL1:
3771
        case WOLFSSL_X448_KYBER_LEVEL3:
3772
        case WOLFSSL_X25519_KYBER_LEVEL3:
3773
        case WOLFSSL_P256_KYBER_LEVEL3:
3774
    #endif
3775
#endif /* WOLFSSL_MLKEM_KYBER */
3776
#endif
3777
0
            return 1;
3778
3779
0
        default:
3780
0
            return 0;
3781
0
    }
3782
0
}
3783
3784
int wolfSSL_UseSupportedCurve(WOLFSSL* ssl, word16 name)
3785
0
{
3786
0
    if (ssl == NULL || !isValidCurveGroup(name))
3787
0
        return BAD_FUNC_ARG;
3788
3789
0
    ssl->options.userCurves = 1;
3790
#if defined(NO_TLS)
3791
    return WOLFSSL_FAILURE;
3792
#else
3793
0
    return TLSX_UseSupportedCurve(&ssl->extensions, name, ssl->heap);
3794
0
#endif /* NO_TLS */
3795
0
}
3796
3797
3798
int wolfSSL_CTX_UseSupportedCurve(WOLFSSL_CTX* ctx, word16 name)
3799
0
{
3800
0
    if (ctx == NULL || !isValidCurveGroup(name))
3801
0
        return BAD_FUNC_ARG;
3802
3803
0
    ctx->userCurves = 1;
3804
#if defined(NO_TLS)
3805
    return WOLFSSL_FAILURE;
3806
#else
3807
0
    return TLSX_UseSupportedCurve(&ctx->extensions, name, ctx->heap);
3808
0
#endif /* NO_TLS */
3809
0
}
3810
3811
#if defined(OPENSSL_EXTRA)
3812
int  wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups,
3813
                                        int count)
3814
{
3815
    int i;
3816
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
3817
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
3818
    if (count == 0) {
3819
        WOLFSSL_MSG("Group count is zero");
3820
        return WOLFSSL_FAILURE;
3821
    }
3822
    for (i = 0; i < count; i++) {
3823
        if (isValidCurveGroup((word16)groups[i])) {
3824
            _groups[i] = groups[i];
3825
        }
3826
#ifdef HAVE_ECC
3827
        else {
3828
            /* groups may be populated with curve NIDs */
3829
            int oid = (int)nid2oid(groups[i], oidCurveType);
3830
            int name = (int)GetCurveByOID(oid);
3831
            if (name == 0) {
3832
                WOLFSSL_MSG("Invalid group name");
3833
                return WOLFSSL_FAILURE;
3834
            }
3835
            _groups[i] = name;
3836
        }
3837
#else
3838
        else {
3839
            WOLFSSL_MSG("Invalid group name");
3840
            return WOLFSSL_FAILURE;
3841
        }
3842
#endif
3843
    }
3844
    return wolfSSL_CTX_set_groups(ctx, _groups, count) == WOLFSSL_SUCCESS ?
3845
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3846
}
3847
3848
int  wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count)
3849
{
3850
    int i;
3851
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
3852
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
3853
    if (count == 0) {
3854
        WOLFSSL_MSG("Group count is zero");
3855
        return WOLFSSL_FAILURE;
3856
    }
3857
    for (i = 0; i < count; i++) {
3858
        if (isValidCurveGroup((word16)groups[i])) {
3859
            _groups[i] = groups[i];
3860
        }
3861
#ifdef HAVE_ECC
3862
        else {
3863
            /* groups may be populated with curve NIDs */
3864
            int oid = (int)nid2oid(groups[i], oidCurveType);
3865
            int name = (int)GetCurveByOID(oid);
3866
            if (name == 0) {
3867
                WOLFSSL_MSG("Invalid group name");
3868
                return WOLFSSL_FAILURE;
3869
            }
3870
            _groups[i] = name;
3871
        }
3872
#else
3873
        else {
3874
            WOLFSSL_MSG("Invalid group name");
3875
            return WOLFSSL_FAILURE;
3876
        }
3877
#endif
3878
    }
3879
    return wolfSSL_set_groups(ssl, _groups, count) == WOLFSSL_SUCCESS ?
3880
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3881
}
3882
#endif /* OPENSSL_EXTRA */
3883
#endif /* HAVE_SUPPORTED_CURVES */
3884
3885
/* Application-Layer Protocol Negotiation */
3886
#ifdef HAVE_ALPN
3887
3888
WOLFSSL_ABI
3889
int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list,
3890
                    word32 protocol_name_listSz, byte options)
3891
{
3892
    char    *list, *ptr = NULL, **token;
3893
    word16  len;
3894
    int     idx = 0;
3895
    int     ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
3896
3897
    WOLFSSL_ENTER("wolfSSL_UseALPN");
3898
3899
    if (ssl == NULL || protocol_name_list == NULL)
3900
        return BAD_FUNC_ARG;
3901
3902
    if (protocol_name_listSz > (WOLFSSL_MAX_ALPN_NUMBER *
3903
                                WOLFSSL_MAX_ALPN_PROTO_NAME_LEN +
3904
                                WOLFSSL_MAX_ALPN_NUMBER)) {
3905
        WOLFSSL_MSG("Invalid arguments, protocol name list too long");
3906
        return BAD_FUNC_ARG;
3907
    }
3908
3909
    if (!(options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) &&
3910
        !(options & WOLFSSL_ALPN_FAILED_ON_MISMATCH)) {
3911
            WOLFSSL_MSG("Invalid arguments, options not supported");
3912
            return BAD_FUNC_ARG;
3913
        }
3914
3915
3916
    list = (char *)XMALLOC(protocol_name_listSz+1, ssl->heap,
3917
                           DYNAMIC_TYPE_ALPN);
3918
    if (list == NULL) {
3919
        WOLFSSL_MSG("Memory failure");
3920
        return MEMORY_ERROR;
3921
    }
3922
3923
    token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1),
3924
        ssl->heap, DYNAMIC_TYPE_ALPN);
3925
    if (token == NULL) {
3926
        XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3927
        WOLFSSL_MSG("Memory failure");
3928
        return MEMORY_ERROR;
3929
    }
3930
    XMEMSET(token, 0, sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1));
3931
3932
    XSTRNCPY(list, protocol_name_list, protocol_name_listSz);
3933
    list[protocol_name_listSz] = '\0';
3934
3935
    /* read all protocol name from the list */
3936
    token[idx] = XSTRTOK(list, ",", &ptr);
3937
    while (idx < WOLFSSL_MAX_ALPN_NUMBER && token[idx] != NULL)
3938
        token[++idx] = XSTRTOK(NULL, ",", &ptr);
3939
3940
    /* add protocol name list in the TLS extension in reverse order */
3941
    while ((idx--) > 0) {
3942
        len = (word16)XSTRLEN(token[idx]);
3943
3944
        ret = TLSX_UseALPN(&ssl->extensions, token[idx], len, options,
3945
                                                                     ssl->heap);
3946
        if (ret != WOLFSSL_SUCCESS) {
3947
            WOLFSSL_MSG("TLSX_UseALPN failure");
3948
            break;
3949
        }
3950
    }
3951
3952
    XFREE(token, ssl->heap, DYNAMIC_TYPE_ALPN);
3953
    XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3954
3955
    return ret;
3956
}
3957
3958
int wolfSSL_ALPN_GetProtocol(WOLFSSL* ssl, char **protocol_name, word16 *size)
3959
{
3960
    return TLSX_ALPN_GetRequest(ssl ? ssl->extensions : NULL,
3961
                               (void **)protocol_name, size);
3962
}
3963
3964
int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, word16 *listSz)
3965
{
3966
    int i, len;
3967
    char *p;
3968
    byte *s;
3969
3970
    if (ssl == NULL || list == NULL || listSz == NULL)
3971
        return BAD_FUNC_ARG;
3972
3973
    if (ssl->alpn_peer_requested == NULL
3974
        || ssl->alpn_peer_requested_length == 0)
3975
        return BUFFER_ERROR;
3976
3977
    /* ssl->alpn_peer_requested are the original bytes sent in a ClientHello,
3978
     * formatted as (len-byte chars+)+. To turn n protocols into a
3979
     * comma-separated C string, one needs (n-1) commas and a final 0 byte
3980
     * which has the same length as the original.
3981
     * The returned length is the strlen() of the C string, so -1 of that. */
3982
    *listSz = ssl->alpn_peer_requested_length-1;
3983
    *list = p = (char *)XMALLOC(ssl->alpn_peer_requested_length, ssl->heap,
3984
                                DYNAMIC_TYPE_TLSX);
3985
    if (p == NULL)
3986
        return MEMORY_ERROR;
3987
3988
    for (i = 0, s = ssl->alpn_peer_requested;
3989
         i < ssl->alpn_peer_requested_length;
3990
         p += len, i += len)
3991
    {
3992
        if (i)
3993
            *p++ = ',';
3994
        len = s[i++];
3995
        /* guard against bad length bytes. */
3996
        if (i + len > ssl->alpn_peer_requested_length) {
3997
            XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
3998
            *list = NULL;
3999
            return WOLFSSL_FAILURE;
4000
        }
4001
        XMEMCPY(p, s + i, (size_t)len);
4002
    }
4003
    *p = 0;
4004
4005
    return WOLFSSL_SUCCESS;
4006
}
4007
4008
4009
/* used to free memory allocated by wolfSSL_ALPN_GetPeerProtocol */
4010
int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list)
4011
{
4012
    if (ssl == NULL) {
4013
        return BAD_FUNC_ARG;
4014
    }
4015
4016
    XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
4017
    *list = NULL;
4018
4019
    return WOLFSSL_SUCCESS;
4020
}
4021
4022
#endif /* HAVE_ALPN */
4023
4024
/* Secure Renegotiation */
4025
#ifdef HAVE_SERVER_RENEGOTIATION_INFO
4026
4027
/* user is forcing ability to use secure renegotiation, we discourage it */
4028
int wolfSSL_UseSecureRenegotiation(WOLFSSL* ssl)
4029
266
{
4030
266
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
4031
#if defined(NO_TLS)
4032
    (void)ssl;
4033
#else
4034
266
    if (ssl)
4035
266
        ret = TLSX_UseSecureRenegotiation(&ssl->extensions, ssl->heap);
4036
0
    else
4037
0
        ret = BAD_FUNC_ARG;
4038
4039
266
    if (ret == WOLFSSL_SUCCESS) {
4040
259
        TLSX* extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
4041
4042
259
        if (extension)
4043
259
            ssl->secure_renegotiation = (SecureRenegotiation*)extension->data;
4044
259
    }
4045
266
#endif /* !NO_TLS */
4046
266
    return ret;
4047
266
}
4048
4049
int wolfSSL_CTX_UseSecureRenegotiation(WOLFSSL_CTX* ctx)
4050
0
{
4051
0
    if (ctx == NULL)
4052
0
        return BAD_FUNC_ARG;
4053
4054
0
    ctx->useSecureReneg = 1;
4055
0
    return WOLFSSL_SUCCESS;
4056
0
}
4057
4058
#ifdef HAVE_SECURE_RENEGOTIATION
4059
/* do a secure renegotiation handshake, user forced, we discourage */
4060
static int _Rehandshake(WOLFSSL* ssl)
4061
{
4062
    int ret;
4063
4064
    if (ssl == NULL)
4065
        return BAD_FUNC_ARG;
4066
4067
    if (IsAtLeastTLSv1_3(ssl->version)) {
4068
        WOLFSSL_MSG("Secure Renegotiation not supported in TLS 1.3");
4069
        return SECURE_RENEGOTIATION_E;
4070
    }
4071
4072
    if (ssl->secure_renegotiation == NULL) {
4073
        WOLFSSL_MSG("Secure Renegotiation not forced on by user");
4074
        return SECURE_RENEGOTIATION_E;
4075
    }
4076
4077
    if (ssl->secure_renegotiation->enabled == 0) {
4078
        WOLFSSL_MSG("Secure Renegotiation not enabled at extension level");
4079
        return SECURE_RENEGOTIATION_E;
4080
    }
4081
4082
#ifdef WOLFSSL_DTLS
4083
    if (ssl->options.dtls && ssl->keys.dtls_epoch == 0xFFFF) {
4084
        WOLFSSL_MSG("Secure Renegotiation not allowed. Epoch would wrap");
4085
        return SECURE_RENEGOTIATION_E;
4086
    }
4087
#endif
4088
4089
    /* If the client started the renegotiation, the server will already
4090
     * have processed the client's hello. */
4091
    if (ssl->options.side != WOLFSSL_SERVER_END ||
4092
        ssl->options.acceptState != ACCEPT_FIRST_REPLY_DONE) {
4093
4094
        if (ssl->options.handShakeState != HANDSHAKE_DONE) {
4095
            if (!ssl->options.handShakeDone) {
4096
                WOLFSSL_MSG("Can't renegotiate until initial "
4097
                            "handshake complete");
4098
                return SECURE_RENEGOTIATION_E;
4099
            }
4100
            else {
4101
                WOLFSSL_MSG("Renegotiation already started. "
4102
                            "Moving it forward.");
4103
                ret = wolfSSL_negotiate(ssl);
4104
                if (ret == WOLFSSL_SUCCESS)
4105
                    ssl->secure_rene_count++;
4106
                return ret;
4107
            }
4108
        }
4109
4110
        /* reset handshake states */
4111
        ssl->options.sendVerify = 0;
4112
        ssl->options.serverState = NULL_STATE;
4113
        ssl->options.clientState = NULL_STATE;
4114
        ssl->options.connectState  = CONNECT_BEGIN;
4115
        ssl->options.acceptState   = ACCEPT_BEGIN_RENEG;
4116
        ssl->options.handShakeState = NULL_STATE;
4117
        ssl->options.processReply  = 0;  /* TODO, move states in internal.h */
4118
4119
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
4120
4121
        ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
4122
4123
#if !defined(NO_WOLFSSL_SERVER) && !defined(WOLFSSL_NO_TLS12)
4124
        if (ssl->options.side == WOLFSSL_SERVER_END) {
4125
            ret = SendHelloRequest(ssl);
4126
            if (ret != 0) {
4127
                ssl->error = ret;
4128
                return WOLFSSL_FATAL_ERROR;
4129
            }
4130
        }
4131
#endif /* !NO_WOLFSSL_SERVER && !WOLFSSL_NO_TLS12 */
4132
4133
        ret = InitHandshakeHashes(ssl);
4134
        if (ret != 0) {
4135
            ssl->error = ret;
4136
            return WOLFSSL_FATAL_ERROR;
4137
        }
4138
    }
4139
    ret = wolfSSL_negotiate(ssl);
4140
    if (ret == WOLFSSL_SUCCESS)
4141
        ssl->secure_rene_count++;
4142
    return ret;
4143
}
4144
4145
4146
/* do a secure renegotiation handshake, user forced, we discourage */
4147
int wolfSSL_Rehandshake(WOLFSSL* ssl)
4148
{
4149
    int ret;
4150
    WOLFSSL_ENTER("wolfSSL_Rehandshake");
4151
4152
    if (ssl == NULL)
4153
        return WOLFSSL_FAILURE;
4154
4155
#ifdef HAVE_SESSION_TICKET
4156
    ret = WOLFSSL_SUCCESS;
4157
#endif
4158
4159
    if (ssl->options.side == WOLFSSL_SERVER_END) {
4160
        /* Reset option to send certificate verify. */
4161
        ssl->options.sendVerify = 0;
4162
        /* Reset resuming flag to do full secure handshake. */
4163
        ssl->options.resuming = 0;
4164
    }
4165
    else {
4166
        /* Reset resuming flag to do full secure handshake. */
4167
        ssl->options.resuming = 0;
4168
        #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_CLIENT)
4169
            /* Clearing the ticket. */
4170
            ret = wolfSSL_UseSessionTicket(ssl);
4171
        #endif
4172
    }
4173
    /* CLIENT/SERVER: Reset peer authentication for full secure handshake. */
4174
    ssl->options.peerAuthGood = 0;
4175
4176
#ifdef HAVE_SESSION_TICKET
4177
    if (ret == WOLFSSL_SUCCESS)
4178
#endif
4179
        ret = _Rehandshake(ssl);
4180
4181
    return ret;
4182
}
4183
4184
4185
#ifndef NO_WOLFSSL_CLIENT
4186
4187
/* do a secure resumption handshake, user forced, we discourage */
4188
int wolfSSL_SecureResume(WOLFSSL* ssl)
4189
{
4190
    WOLFSSL_ENTER("wolfSSL_SecureResume");
4191
4192
    if (ssl == NULL)
4193
        return BAD_FUNC_ARG;
4194
4195
    if (ssl->options.side == WOLFSSL_SERVER_END) {
4196
        ssl->error = SIDE_ERROR;
4197
        return WOLFSSL_FATAL_ERROR;
4198
    }
4199
4200
    return _Rehandshake(ssl);
4201
}
4202
4203
#endif /* NO_WOLFSSL_CLIENT */
4204
4205
#endif /* HAVE_SECURE_RENEGOTIATION */
4206
4207
long wolfSSL_SSL_get_secure_renegotiation_support(WOLFSSL* ssl)
4208
0
{
4209
0
    WOLFSSL_ENTER("wolfSSL_SSL_get_secure_renegotiation_support");
4210
4211
0
    if (!ssl || !ssl->secure_renegotiation)
4212
0
        return WOLFSSL_FAILURE;
4213
0
    return ssl->secure_renegotiation->enabled;
4214
0
}
4215
4216
#endif /* HAVE_SECURE_RENEGOTIATION_INFO */
4217
4218
#if defined(HAVE_SESSION_TICKET)
4219
/* Session Ticket */
4220
4221
#if !defined(NO_WOLFSSL_SERVER)
4222
int wolfSSL_CTX_NoTicketTLSv12(WOLFSSL_CTX* ctx)
4223
{
4224
    if (ctx == NULL)
4225
        return BAD_FUNC_ARG;
4226
4227
    ctx->noTicketTls12 = 1;
4228
4229
    return WOLFSSL_SUCCESS;
4230
}
4231
4232
int wolfSSL_NoTicketTLSv12(WOLFSSL* ssl)
4233
{
4234
    if (ssl == NULL)
4235
        return BAD_FUNC_ARG;
4236
4237
    ssl->options.noTicketTls12 = 1;
4238
4239
    return WOLFSSL_SUCCESS;
4240
}
4241
4242
/* WOLFSSL_SUCCESS on ok */
4243
int wolfSSL_CTX_set_TicketEncCb(WOLFSSL_CTX* ctx, SessionTicketEncCb cb)
4244
{
4245
    if (ctx == NULL)
4246
        return BAD_FUNC_ARG;
4247
4248
    ctx->ticketEncCb = cb;
4249
4250
    return WOLFSSL_SUCCESS;
4251
}
4252
4253
/* set hint interval, WOLFSSL_SUCCESS on ok */
4254
int wolfSSL_CTX_set_TicketHint(WOLFSSL_CTX* ctx, int hint)
4255
{
4256
    if (ctx == NULL)
4257
        return BAD_FUNC_ARG;
4258
4259
    ctx->ticketHint = hint;
4260
4261
    return WOLFSSL_SUCCESS;
4262
}
4263
4264
/* set user context, WOLFSSL_SUCCESS on ok */
4265
int wolfSSL_CTX_set_TicketEncCtx(WOLFSSL_CTX* ctx, void* userCtx)
4266
{
4267
    if (ctx == NULL)
4268
        return BAD_FUNC_ARG;
4269
4270
    ctx->ticketEncCtx = userCtx;
4271
4272
    return WOLFSSL_SUCCESS;
4273
}
4274
4275
/* get user context - returns userCtx on success, NULL on failure */
4276
void* wolfSSL_CTX_get_TicketEncCtx(WOLFSSL_CTX* ctx)
4277
{
4278
    if (ctx == NULL)
4279
        return NULL;
4280
4281
    return ctx->ticketEncCtx;
4282
}
4283
4284
#ifdef WOLFSSL_TLS13
4285
/* set the maximum number of tickets to send
4286
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on fail
4287
 */
4288
int wolfSSL_CTX_set_num_tickets(WOLFSSL_CTX* ctx, size_t mxTickets)
4289
{
4290
    if (ctx == NULL)
4291
        return WOLFSSL_FAILURE;
4292
4293
    ctx->maxTicketTls13 = (unsigned int)mxTickets;
4294
    return WOLFSSL_SUCCESS;
4295
}
4296
4297
/* get the maximum number of tickets to send
4298
 * return number of tickets set to be sent
4299
 */
4300
size_t wolfSSL_CTX_get_num_tickets(WOLFSSL_CTX* ctx)
4301
{
4302
    if (ctx == NULL)
4303
        return 0;
4304
4305
    return (size_t)ctx->maxTicketTls13;
4306
}
4307
#endif /* WOLFSSL_TLS13 */
4308
#endif /* !NO_WOLFSSL_SERVER */
4309
4310
#if !defined(NO_WOLFSSL_CLIENT)
4311
int wolfSSL_UseSessionTicket(WOLFSSL* ssl)
4312
{
4313
    if (ssl == NULL)
4314
        return BAD_FUNC_ARG;
4315
4316
    return TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
4317
}
4318
4319
int wolfSSL_CTX_UseSessionTicket(WOLFSSL_CTX* ctx)
4320
{
4321
    if (ctx == NULL)
4322
        return BAD_FUNC_ARG;
4323
4324
    return TLSX_UseSessionTicket(&ctx->extensions, NULL, ctx->heap);
4325
}
4326
4327
int wolfSSL_get_SessionTicket(WOLFSSL* ssl, byte* buf, word32* bufSz)
4328
{
4329
    if (ssl == NULL || bufSz == NULL)
4330
        return BAD_FUNC_ARG;
4331
4332
    if (*bufSz == 0 && buf == NULL) {
4333
        *bufSz = ssl->session->ticketLen;
4334
        return LENGTH_ONLY_E;
4335
    }
4336
4337
    if (buf == NULL)
4338
        return BAD_FUNC_ARG;
4339
4340
    if (ssl->session->ticketLen <= *bufSz) {
4341
        XMEMCPY(buf, ssl->session->ticket, ssl->session->ticketLen);
4342
        *bufSz = ssl->session->ticketLen;
4343
    }
4344
    else
4345
        *bufSz = 0;
4346
4347
    return WOLFSSL_SUCCESS;
4348
}
4349
4350
int wolfSSL_set_SessionTicket(WOLFSSL* ssl, const byte* buf,
4351
                                          word32 bufSz)
4352
{
4353
    if (ssl == NULL || (buf == NULL && bufSz > 0))
4354
        return BAD_FUNC_ARG;
4355
4356
    if (bufSz > 0) {
4357
        /* Ticket will fit into static ticket */
4358
        if (bufSz <= SESSION_TICKET_LEN) {
4359
            if (ssl->session->ticketLenAlloc > 0) {
4360
                XFREE(ssl->session->ticket, ssl->session->heap,
4361
                      DYNAMIC_TYPE_SESSION_TICK);
4362
                ssl->session->ticketLenAlloc = 0;
4363
                ssl->session->ticket = ssl->session->staticTicket;
4364
            }
4365
        }
4366
        else { /* Ticket requires dynamic ticket storage */
4367
            /* is dyn buffer big enough */
4368
            if (ssl->session->ticketLen < bufSz) {
4369
                if (ssl->session->ticketLenAlloc > 0) {
4370
                    XFREE(ssl->session->ticket, ssl->session->heap,
4371
                          DYNAMIC_TYPE_SESSION_TICK);
4372
                }
4373
                ssl->session->ticket = (byte*)XMALLOC(bufSz, ssl->session->heap,
4374
                        DYNAMIC_TYPE_SESSION_TICK);
4375
                if(ssl->session->ticket == NULL) {
4376
                    ssl->session->ticket = ssl->session->staticTicket;
4377
                    ssl->session->ticketLenAlloc = 0;
4378
                    return MEMORY_ERROR;
4379
                }
4380
                ssl->session->ticketLenAlloc = (word16)bufSz;
4381
            }
4382
        }
4383
        XMEMCPY(ssl->session->ticket, buf, bufSz);
4384
    }
4385
    ssl->session->ticketLen = (word16)bufSz;
4386
4387
    return WOLFSSL_SUCCESS;
4388
}
4389
4390
4391
int wolfSSL_set_SessionTicket_cb(WOLFSSL* ssl,
4392
                                 CallbackSessionTicket cb, void* ctx)
4393
{
4394
    if (ssl == NULL)
4395
        return BAD_FUNC_ARG;
4396
4397
    ssl->session_ticket_cb = cb;
4398
    ssl->session_ticket_ctx = ctx;
4399
4400
    return WOLFSSL_SUCCESS;
4401
}
4402
#endif /* !NO_WOLFSSL_CLIENT */
4403
4404
#endif /* HAVE_SESSION_TICKET */
4405
4406
4407
#ifdef HAVE_EXTENDED_MASTER
4408
#ifndef NO_WOLFSSL_CLIENT
4409
4410
int wolfSSL_CTX_DisableExtendedMasterSecret(WOLFSSL_CTX* ctx)
4411
0
{
4412
0
    if (ctx == NULL)
4413
0
        return BAD_FUNC_ARG;
4414
4415
0
    ctx->haveEMS = 0;
4416
4417
0
    return WOLFSSL_SUCCESS;
4418
0
}
4419
4420
4421
int wolfSSL_DisableExtendedMasterSecret(WOLFSSL* ssl)
4422
0
{
4423
0
    if (ssl == NULL)
4424
0
        return BAD_FUNC_ARG;
4425
4426
0
    ssl->options.haveEMS = 0;
4427
4428
0
    return WOLFSSL_SUCCESS;
4429
0
}
4430
4431
#endif
4432
#endif
4433
4434
4435
#ifndef WOLFSSL_LEANPSK
4436
4437
int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags)
4438
0
{
4439
0
    int ret;
4440
0
    int oldFlags;
4441
4442
0
    WOLFSSL_ENTER("wolfSSL_send");
4443
4444
0
    if (ssl == NULL || data == NULL || sz < 0)
4445
0
        return BAD_FUNC_ARG;
4446
4447
0
    oldFlags = ssl->wflags;
4448
4449
0
    ssl->wflags = flags;
4450
0
    ret = wolfSSL_write(ssl, data, sz);
4451
0
    ssl->wflags = oldFlags;
4452
4453
0
    WOLFSSL_LEAVE("wolfSSL_send", ret);
4454
4455
0
    return ret;
4456
0
}
4457
4458
4459
int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags)
4460
0
{
4461
0
    int ret;
4462
0
    int oldFlags;
4463
4464
0
    WOLFSSL_ENTER("wolfSSL_recv");
4465
4466
0
    if (ssl == NULL || data == NULL || sz < 0)
4467
0
        return BAD_FUNC_ARG;
4468
4469
0
    oldFlags = ssl->rflags;
4470
4471
0
    ssl->rflags = flags;
4472
0
    ret = wolfSSL_read(ssl, data, sz);
4473
0
    ssl->rflags = oldFlags;
4474
4475
0
    WOLFSSL_LEAVE("wolfSSL_recv", ret);
4476
4477
0
    return ret;
4478
0
}
4479
#endif
4480
4481
int wolfSSL_SendUserCanceled(WOLFSSL* ssl)
4482
0
{
4483
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
4484
0
    WOLFSSL_ENTER("wolfSSL_recv");
4485
4486
0
    if (ssl != NULL) {
4487
0
        ssl->error = SendAlert(ssl, alert_warning, user_canceled);
4488
0
        if (ssl->error < 0) {
4489
0
            WOLFSSL_ERROR(ssl->error);
4490
0
        }
4491
0
        else {
4492
0
            ret = wolfSSL_shutdown(ssl);
4493
0
        }
4494
0
    }
4495
4496
0
    WOLFSSL_LEAVE("wolfSSL_SendUserCanceled", ret);
4497
4498
0
    return ret;
4499
0
}
4500
4501
/* WOLFSSL_SUCCESS on ok */
4502
WOLFSSL_ABI
4503
int wolfSSL_shutdown(WOLFSSL* ssl)
4504
0
{
4505
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
4506
0
    WOLFSSL_ENTER("wolfSSL_shutdown");
4507
4508
0
    if (ssl == NULL)
4509
0
        return WOLFSSL_FATAL_ERROR;
4510
4511
0
    if (ssl->options.quietShutdown) {
4512
0
        WOLFSSL_MSG("quiet shutdown, no close notify sent");
4513
0
        ret = WOLFSSL_SUCCESS;
4514
0
    }
4515
0
    else {
4516
4517
        /* Try to flush the buffer first, it might contain the alert */
4518
0
        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE) &&
4519
0
            ssl->buffers.outputBuffer.length > 0) {
4520
0
            ret = SendBuffered(ssl);
4521
0
            if (ret != 0) {
4522
0
                ssl->error = ret;
4523
                /* for error tracing */
4524
0
                if (ret != WC_NO_ERR_TRACE(WANT_WRITE))
4525
0
                    WOLFSSL_ERROR(ret);
4526
0
                ret = WOLFSSL_FATAL_ERROR;
4527
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4528
0
                return ret;
4529
0
            }
4530
4531
0
            ssl->error = WOLFSSL_ERROR_NONE;
4532
            /* we succeeded in sending the alert now */
4533
0
            if (ssl->options.sentNotify)  {
4534
                /* just after we send the alert, if we didn't receive the alert
4535
                 * from the other peer yet, return WOLFSSL_STHUDOWN_NOT_DONE */
4536
0
                if (!ssl->options.closeNotify) {
4537
0
                    ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4538
0
                    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4539
0
                    return ret;
4540
0
                }
4541
0
                else {
4542
0
                    ssl->options.shutdownDone = 1;
4543
0
                    ret = WOLFSSL_SUCCESS;
4544
0
                }
4545
0
            }
4546
0
        }
4547
4548
        /* try to send close notify, not an error if can't */
4549
0
        if (!ssl->options.isClosed && !ssl->options.connReset &&
4550
0
                                      !ssl->options.sentNotify) {
4551
0
            ssl->error = SendAlert(ssl, alert_warning, close_notify);
4552
4553
            /* the alert is now sent or sitting in the buffer,
4554
             * where will be sent eventually */
4555
0
            if (ssl->error == 0 || ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4556
0
                ssl->options.sentNotify = 1;
4557
4558
0
            if (ssl->error < 0) {
4559
0
                WOLFSSL_ERROR(ssl->error);
4560
0
                return WOLFSSL_FATAL_ERROR;
4561
0
            }
4562
4563
0
            if (ssl->options.closeNotify) {
4564
0
                ret = WOLFSSL_SUCCESS;
4565
0
                ssl->options.shutdownDone = 1;
4566
0
            }
4567
0
            else {
4568
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4569
0
                WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4570
0
                return ret;
4571
0
            }
4572
0
        }
4573
4574
#ifdef WOLFSSL_SHUTDOWNONCE
4575
        if (ssl->options.isClosed || ssl->options.connReset) {
4576
            /* Shutdown has already occurred.
4577
             * Caller is free to ignore this error. */
4578
            return SSL_SHUTDOWN_ALREADY_DONE_E;
4579
        }
4580
#endif
4581
4582
        /* wolfSSL_shutdown called again for bidirectional shutdown */
4583
0
        if (ssl->options.sentNotify && !ssl->options.closeNotify) {
4584
0
            ret = ProcessReply(ssl);
4585
0
            if ((ret == WC_NO_ERR_TRACE(ZERO_RETURN)) ||
4586
0
                (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))) {
4587
                /* simulate OpenSSL behavior */
4588
0
                ssl->options.shutdownDone = 1;
4589
                /* Clear error */
4590
0
                ssl->error = WOLFSSL_ERROR_NONE;
4591
0
                ret = WOLFSSL_SUCCESS;
4592
0
            }
4593
0
            else if (ret == WC_NO_ERR_TRACE(MEMORY_E)) {
4594
0
                ret = WOLFSSL_FATAL_ERROR;
4595
0
            }
4596
0
            else if (ret == WC_NO_ERR_TRACE(WANT_READ)) {
4597
0
                ssl->error = ret;
4598
0
                ret = WOLFSSL_FATAL_ERROR;
4599
0
            }
4600
0
            else if (ssl->error == WOLFSSL_ERROR_NONE) {
4601
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
4602
0
            }
4603
0
            else {
4604
0
                WOLFSSL_ERROR(ssl->error);
4605
0
                ret = WOLFSSL_FATAL_ERROR;
4606
0
            }
4607
0
        }
4608
0
    }
4609
4610
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
4611
    /* reset WOLFSSL structure state for possible reuse */
4612
    if (ret == WOLFSSL_SUCCESS) {
4613
        if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) {
4614
            WOLFSSL_MSG("could not clear WOLFSSL");
4615
            ret = WOLFSSL_FATAL_ERROR;
4616
        }
4617
    }
4618
#endif
4619
4620
0
    WOLFSSL_LEAVE("wolfSSL_shutdown", ret);
4621
4622
0
    return ret;
4623
0
}
4624
#endif /* !NO_TLS */
4625
4626
/* get current error state value */
4627
int wolfSSL_state(WOLFSSL* ssl)
4628
0
{
4629
0
    if (ssl == NULL) {
4630
0
        return BAD_FUNC_ARG;
4631
0
    }
4632
4633
0
    return ssl->error;
4634
0
}
4635
4636
4637
WOLFSSL_ABI
4638
int wolfSSL_get_error(WOLFSSL* ssl, int ret)
4639
0
{
4640
0
    WOLFSSL_ENTER("wolfSSL_get_error");
4641
4642
0
    if (ret > 0)
4643
0
        return WOLFSSL_ERROR_NONE;
4644
0
    if (ssl == NULL)
4645
0
        return BAD_FUNC_ARG;
4646
4647
0
    WOLFSSL_LEAVE("wolfSSL_get_error", ssl->error);
4648
4649
    /* make sure converted types are handled in SetErrorString() too */
4650
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4651
0
        return WOLFSSL_ERROR_WANT_READ;         /* convert to OpenSSL type */
4652
0
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4653
0
        return WOLFSSL_ERROR_WANT_WRITE;        /* convert to OpenSSL type */
4654
0
    else if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) ||
4655
0
             ssl->options.shutdownDone)
4656
0
        return WOLFSSL_ERROR_ZERO_RETURN;       /* convert to OpenSSL type */
4657
#ifdef OPENSSL_EXTRA
4658
    else if (ssl->error == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
4659
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
4660
    else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E))
4661
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
4662
#endif
4663
0
    return ssl->error;
4664
0
}
4665
4666
4667
/* retrieve alert history, WOLFSSL_SUCCESS on ok */
4668
int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
4669
0
{
4670
0
    if (ssl && h) {
4671
0
        *h = ssl->alert_history;
4672
0
    }
4673
0
    return WOLFSSL_SUCCESS;
4674
0
}
4675
4676
#ifdef OPENSSL_EXTRA
4677
/* returns SSL_WRITING, SSL_READING or SSL_NOTHING */
4678
int wolfSSL_want(WOLFSSL* ssl)
4679
{
4680
    int rw_state = WOLFSSL_NOTHING;
4681
    if (ssl) {
4682
        if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4683
            rw_state = WOLFSSL_READING;
4684
        else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4685
            rw_state = WOLFSSL_WRITING;
4686
    }
4687
    return rw_state;
4688
}
4689
#endif
4690
4691
/* return TRUE if current error is want read */
4692
int wolfSSL_want_read(WOLFSSL* ssl)
4693
0
{
4694
0
    WOLFSSL_ENTER("wolfSSL_want_read");
4695
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
4696
0
        return 1;
4697
4698
0
    return 0;
4699
0
}
4700
4701
/* return TRUE if current error is want write */
4702
int wolfSSL_want_write(WOLFSSL* ssl)
4703
0
{
4704
0
    WOLFSSL_ENTER("wolfSSL_want_write");
4705
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
4706
0
        return 1;
4707
4708
0
    return 0;
4709
0
}
4710
4711
char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data)
4712
0
{
4713
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string");
4714
0
    if (data) {
4715
0
        SetErrorString((int)errNumber, data);
4716
0
        return data;
4717
0
    }
4718
0
    else {
4719
0
        static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0};
4720
0
        SetErrorString((int)errNumber, tmp);
4721
0
        return tmp;
4722
0
    }
4723
0
}
4724
4725
4726
void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
4727
0
{
4728
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string_n");
4729
0
    if (len >= WOLFSSL_MAX_ERROR_SZ)
4730
0
        wolfSSL_ERR_error_string(e, buf);
4731
0
    else {
4732
0
        WOLFSSL_MSG("Error buffer too short, truncating");
4733
0
        if (len) {
4734
0
            char tmp[WOLFSSL_MAX_ERROR_SZ];
4735
0
            wolfSSL_ERR_error_string(e, tmp);
4736
0
            XMEMCPY(buf, tmp, len-1);
4737
0
            buf[len-1] = '\0';
4738
0
        }
4739
0
    }
4740
0
}
4741
4742
4743
/* don't free temporary arrays at end of handshake */
4744
void wolfSSL_KeepArrays(WOLFSSL* ssl)
4745
0
{
4746
0
    if (ssl)
4747
0
        ssl->options.saveArrays = 1;
4748
0
}
4749
4750
4751
/* user doesn't need temporary arrays anymore, Free */
4752
void wolfSSL_FreeArrays(WOLFSSL* ssl)
4753
0
{
4754
0
    if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
4755
0
        ssl->options.saveArrays = 0;
4756
0
        FreeArrays(ssl, 1);
4757
0
    }
4758
0
}
4759
4760
/* Set option to indicate that the resources are not to be freed after
4761
 * handshake.
4762
 *
4763
 * ssl  The SSL/TLS object.
4764
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4765
 */
4766
int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
4767
0
{
4768
0
    if (ssl == NULL)
4769
0
        return BAD_FUNC_ARG;
4770
4771
0
    ssl->options.keepResources = 1;
4772
4773
0
    return 0;
4774
0
}
4775
4776
/* Free the handshake resources after handshake.
4777
 *
4778
 * ssl  The SSL/TLS object.
4779
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4780
 */
4781
int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
4782
0
{
4783
0
    if (ssl == NULL)
4784
0
        return BAD_FUNC_ARG;
4785
4786
0
    FreeHandshakeResources(ssl);
4787
4788
0
    return 0;
4789
0
}
4790
4791
/* Use the client's order of preference when matching cipher suites.
4792
 *
4793
 * ssl  The SSL/TLS context object.
4794
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4795
 */
4796
int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
4797
0
{
4798
0
    if (ctx == NULL)
4799
0
        return BAD_FUNC_ARG;
4800
4801
0
    ctx->useClientOrder = 1;
4802
4803
0
    return 0;
4804
0
}
4805
4806
/* Use the client's order of preference when matching cipher suites.
4807
 *
4808
 * ssl  The SSL/TLS object.
4809
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
4810
 */
4811
int wolfSSL_UseClientSuites(WOLFSSL* ssl)
4812
0
{
4813
0
    if (ssl == NULL)
4814
0
        return BAD_FUNC_ARG;
4815
4816
0
    ssl->options.useClientOrder = 1;
4817
4818
0
    return 0;
4819
0
}
4820
4821
#ifdef WOLFSSL_DTLS
4822
const byte* wolfSSL_GetDtlsMacSecret(WOLFSSL* ssl, int verify, int epochOrder)
4823
{
4824
#ifndef WOLFSSL_AEAD_ONLY
4825
    Keys* keys = NULL;
4826
4827
    (void)epochOrder;
4828
4829
    if (ssl == NULL)
4830
        return NULL;
4831
4832
#ifdef HAVE_SECURE_RENEGOTIATION
4833
    switch (epochOrder) {
4834
    case PEER_ORDER:
4835
        if (IsDtlsMsgSCRKeys(ssl))
4836
            keys = &ssl->secure_renegotiation->tmp_keys;
4837
        else
4838
            keys = &ssl->keys;
4839
        break;
4840
    case PREV_ORDER:
4841
        keys = &ssl->keys;
4842
        break;
4843
    case CUR_ORDER:
4844
        if (DtlsUseSCRKeys(ssl))
4845
            keys = &ssl->secure_renegotiation->tmp_keys;
4846
        else
4847
            keys = &ssl->keys;
4848
        break;
4849
    default:
4850
        WOLFSSL_MSG("Unknown epoch order");
4851
        return NULL;
4852
    }
4853
#else
4854
    keys = &ssl->keys;
4855
#endif
4856
4857
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
4858
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
4859
        return keys->client_write_MAC_secret;
4860
    else
4861
        return keys->server_write_MAC_secret;
4862
#else
4863
    (void)ssl;
4864
    (void)verify;
4865
    (void)epochOrder;
4866
4867
    return NULL;
4868
#endif
4869
}
4870
#endif /* WOLFSSL_DTLS */
4871
4872
const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
4873
614
{
4874
614
#ifndef WOLFSSL_AEAD_ONLY
4875
614
    if (ssl == NULL)
4876
0
        return NULL;
4877
4878
614
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
4879
148
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
4880
514
        return ssl->keys.client_write_MAC_secret;
4881
100
    else
4882
100
        return ssl->keys.server_write_MAC_secret;
4883
#else
4884
    (void)ssl;
4885
    (void)verify;
4886
4887
    return NULL;
4888
#endif
4889
614
}
4890
4891
int wolfSSL_GetSide(WOLFSSL* ssl)
4892
0
{
4893
0
    if (ssl)
4894
0
        return ssl->options.side;
4895
4896
0
    return BAD_FUNC_ARG;
4897
0
}
4898
4899
#ifdef ATOMIC_USER
4900
4901
void  wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
4902
{
4903
    if (ctx)
4904
        ctx->MacEncryptCb = cb;
4905
}
4906
4907
4908
void  wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
4909
{
4910
    if (ssl)
4911
        ssl->MacEncryptCtx = ctx;
4912
}
4913
4914
4915
void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
4916
{
4917
    if (ssl)
4918
        return ssl->MacEncryptCtx;
4919
4920
    return NULL;
4921
}
4922
4923
4924
void  wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
4925
{
4926
    if (ctx)
4927
        ctx->DecryptVerifyCb = cb;
4928
}
4929
4930
4931
void  wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
4932
{
4933
    if (ssl)
4934
        ssl->DecryptVerifyCtx = ctx;
4935
}
4936
4937
4938
void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
4939
{
4940
    if (ssl)
4941
        return ssl->DecryptVerifyCtx;
4942
4943
    return NULL;
4944
}
4945
4946
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
4947
/**
4948
 * Set the callback, against the context, that encrypts then MACs.
4949
 *
4950
 * ctx  SSL/TLS context.
4951
 * cb   Callback function to use with Encrypt-Then-MAC.
4952
 */
4953
void  wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
4954
{
4955
    if (ctx)
4956
        ctx->EncryptMacCb = cb;
4957
}
4958
4959
/**
4960
 * Set the context to use with callback that encrypts then MACs.
4961
 *
4962
 * ssl  SSL/TLS object.
4963
 * ctx  Callback function's context.
4964
 */
4965
void  wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
4966
{
4967
    if (ssl)
4968
        ssl->EncryptMacCtx = ctx;
4969
}
4970
4971
/**
4972
 * Get the context being used with callback that encrypts then MACs.
4973
 *
4974
 * ssl  SSL/TLS object.
4975
 * returns callback function's context or NULL if SSL/TLS object is NULL.
4976
 */
4977
void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
4978
{
4979
    if (ssl)
4980
        return ssl->EncryptMacCtx;
4981
4982
    return NULL;
4983
}
4984
4985
4986
/**
4987
 * Set the callback, against the context, that MAC verifies then decrypts.
4988
 *
4989
 * ctx  SSL/TLS context.
4990
 * cb   Callback function to use with Encrypt-Then-MAC.
4991
 */
4992
void  wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
4993
{
4994
    if (ctx)
4995
        ctx->VerifyDecryptCb = cb;
4996
}
4997
4998
/**
4999
 * Set the context to use with callback that MAC verifies then decrypts.
5000
 *
5001
 * ssl  SSL/TLS object.
5002
 * ctx  Callback function's context.
5003
 */
5004
void  wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
5005
{
5006
    if (ssl)
5007
        ssl->VerifyDecryptCtx = ctx;
5008
}
5009
5010
/**
5011
 * Get the context being used with callback that MAC verifies then decrypts.
5012
 *
5013
 * ssl  SSL/TLS object.
5014
 * returns callback function's context or NULL if SSL/TLS object is NULL.
5015
 */
5016
void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
5017
{
5018
    if (ssl)
5019
        return ssl->VerifyDecryptCtx;
5020
5021
    return NULL;
5022
}
5023
#endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
5024
5025
5026
5027
const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
5028
{
5029
    if (ssl)
5030
        return ssl->keys.client_write_key;
5031
5032
    return NULL;
5033
}
5034
5035
5036
const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
5037
{
5038
    if (ssl)
5039
        return ssl->keys.client_write_IV;
5040
5041
    return NULL;
5042
}
5043
5044
5045
const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
5046
{
5047
    if (ssl)
5048
        return ssl->keys.server_write_key;
5049
5050
    return NULL;
5051
}
5052
5053
5054
const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
5055
{
5056
    if (ssl)
5057
        return ssl->keys.server_write_IV;
5058
5059
    return NULL;
5060
}
5061
5062
int wolfSSL_GetKeySize(WOLFSSL* ssl)
5063
{
5064
    if (ssl)
5065
        return ssl->specs.key_size;
5066
5067
    return BAD_FUNC_ARG;
5068
}
5069
5070
5071
int wolfSSL_GetIVSize(WOLFSSL* ssl)
5072
{
5073
    if (ssl)
5074
        return ssl->specs.iv_size;
5075
5076
    return BAD_FUNC_ARG;
5077
}
5078
5079
5080
int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
5081
{
5082
    if (ssl)
5083
        return ssl->specs.bulk_cipher_algorithm;
5084
5085
    return BAD_FUNC_ARG;
5086
}
5087
5088
5089
int wolfSSL_GetCipherType(WOLFSSL* ssl)
5090
{
5091
    if (ssl == NULL)
5092
        return BAD_FUNC_ARG;
5093
5094
#ifndef WOLFSSL_AEAD_ONLY
5095
    if (ssl->specs.cipher_type == block)
5096
        return WOLFSSL_BLOCK_TYPE;
5097
    if (ssl->specs.cipher_type == stream)
5098
        return WOLFSSL_STREAM_TYPE;
5099
#endif
5100
    if (ssl->specs.cipher_type == aead)
5101
        return WOLFSSL_AEAD_TYPE;
5102
5103
    return WOLFSSL_FATAL_ERROR;
5104
}
5105
5106
5107
int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
5108
{
5109
    if (ssl == NULL)
5110
        return BAD_FUNC_ARG;
5111
5112
    return ssl->specs.block_size;
5113
}
5114
5115
5116
int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
5117
{
5118
    if (ssl == NULL)
5119
        return BAD_FUNC_ARG;
5120
5121
    return ssl->specs.aead_mac_size;
5122
}
5123
5124
5125
int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
5126
{
5127
    if (ssl == NULL)
5128
        return BAD_FUNC_ARG;
5129
5130
    if (ssl->options.tls1_1)
5131
        return 1;
5132
5133
    return 0;
5134
}
5135
5136
5137
5138
int wolfSSL_GetHmacSize(WOLFSSL* ssl)
5139
{
5140
    /* AEAD ciphers don't have HMAC keys */
5141
    if (ssl)
5142
        return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
5143
5144
    return BAD_FUNC_ARG;
5145
}
5146
5147
#ifdef WORD64_AVAILABLE
5148
int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
5149
{
5150
    if ((ssl == NULL) || (seq == NULL))
5151
        return BAD_FUNC_ARG;
5152
5153
    *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
5154
                    ssl->keys.peer_sequence_number_lo;
5155
    return !(*seq);
5156
}
5157
5158
int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
5159
{
5160
    if ((ssl == NULL) || (seq == NULL))
5161
        return BAD_FUNC_ARG;
5162
5163
    *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
5164
                    ssl->keys.sequence_number_lo;
5165
    return !(*seq);
5166
}
5167
#endif
5168
5169
#endif /* ATOMIC_USER */
5170
5171
#ifndef NO_CERTS
5172
WOLFSSL_CERT_MANAGER* wolfSSL_CTX_GetCertManager(WOLFSSL_CTX* ctx)
5173
0
{
5174
0
    WOLFSSL_CERT_MANAGER* cm = NULL;
5175
0
    if (ctx)
5176
0
        cm = ctx->cm;
5177
0
    return cm;
5178
0
}
5179
#endif /* NO_CERTS */
5180
5181
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) \
5182
    && defined(XFPRINTF)
5183
5184
void wolfSSL_ERR_print_errors_fp(XFILE fp, int err)
5185
0
{
5186
0
    char data[WOLFSSL_MAX_ERROR_SZ + 1];
5187
5188
0
    WOLFSSL_ENTER("wolfSSL_ERR_print_errors_fp");
5189
0
    SetErrorString(err, data);
5190
0
    if (XFPRINTF(fp, "%s", data) < 0)
5191
0
        WOLFSSL_MSG("fprintf failed in wolfSSL_ERR_print_errors_fp");
5192
0
}
5193
5194
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
5195
void wolfSSL_ERR_dump_errors_fp(XFILE fp)
5196
{
5197
    wc_ERR_print_errors_fp(fp);
5198
}
5199
5200
void wolfSSL_ERR_print_errors_cb (int (*cb)(const char *str, size_t len,
5201
                                            void *u), void *u)
5202
{
5203
    wc_ERR_print_errors_cb(cb, u);
5204
}
5205
#endif
5206
#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM && XFPRINTF */
5207
5208
/*
5209
 * TODO This ssl parameter needs to be changed to const once our ABI checker
5210
 *      stops flagging qualifier additions as ABI breaking.
5211
 */
5212
WOLFSSL_ABI
5213
int wolfSSL_pending(WOLFSSL* ssl)
5214
0
{
5215
0
    WOLFSSL_ENTER("wolfSSL_pending");
5216
0
    if (ssl == NULL)
5217
0
        return WOLFSSL_FAILURE;
5218
5219
0
    return (int)ssl->buffers.clearOutputBuffer.length;
5220
0
}
5221
5222
int wolfSSL_has_pending(const WOLFSSL* ssl)
5223
0
{
5224
0
    WOLFSSL_ENTER("wolfSSL_has_pending");
5225
0
    if (ssl == NULL)
5226
0
        return WOLFSSL_FAILURE;
5227
5228
0
    return ssl->buffers.clearOutputBuffer.length > 0;
5229
0
}
5230
5231
#ifndef WOLFSSL_LEANPSK
5232
/* turn on handshake group messages for context */
5233
int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
5234
0
{
5235
0
    if (ctx == NULL)
5236
0
       return BAD_FUNC_ARG;
5237
5238
0
    ctx->groupMessages = 1;
5239
5240
0
    return WOLFSSL_SUCCESS;
5241
0
}
5242
5243
int wolfSSL_CTX_clear_group_messages(WOLFSSL_CTX* ctx)
5244
0
{
5245
0
    if (ctx == NULL)
5246
0
       return BAD_FUNC_ARG;
5247
5248
0
    ctx->groupMessages = 0;
5249
5250
0
    return WOLFSSL_SUCCESS;
5251
0
}
5252
#endif
5253
5254
5255
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
5256
/* connect enough to get peer cert chain */
5257
int wolfSSL_connect_cert(WOLFSSL* ssl)
5258
0
{
5259
0
    int  ret;
5260
5261
0
    if (ssl == NULL)
5262
0
        return WOLFSSL_FAILURE;
5263
5264
0
    ssl->options.certOnly = 1;
5265
0
    ret = wolfSSL_connect(ssl);
5266
0
    ssl->options.certOnly   = 0;
5267
5268
0
    return ret;
5269
0
}
5270
#endif
5271
5272
5273
#ifndef WOLFSSL_LEANPSK
5274
/* turn on handshake group messages for ssl object */
5275
int wolfSSL_set_group_messages(WOLFSSL* ssl)
5276
0
{
5277
0
    if (ssl == NULL)
5278
0
       return BAD_FUNC_ARG;
5279
5280
0
    ssl->options.groupMessages = 1;
5281
5282
0
    return WOLFSSL_SUCCESS;
5283
0
}
5284
5285
int wolfSSL_clear_group_messages(WOLFSSL* ssl)
5286
0
{
5287
0
    if (ssl == NULL)
5288
0
       return BAD_FUNC_ARG;
5289
5290
0
    ssl->options.groupMessages = 0;
5291
5292
0
    return WOLFSSL_SUCCESS;
5293
0
}
5294
5295
/* make minVersion the internal equivalent SSL version */
5296
static int SetMinVersionHelper(byte* minVersion, int version)
5297
0
{
5298
0
    (void)minVersion;
5299
5300
0
    switch (version) {
5301
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
5302
        case WOLFSSL_SSLV3:
5303
            *minVersion = SSLv3_MINOR;
5304
            break;
5305
#endif
5306
5307
0
#ifndef NO_TLS
5308
    #ifndef NO_OLD_TLS
5309
        #ifdef WOLFSSL_ALLOW_TLSV10
5310
        case WOLFSSL_TLSV1:
5311
            *minVersion = TLSv1_MINOR;
5312
            break;
5313
        #endif
5314
5315
        case WOLFSSL_TLSV1_1:
5316
            *minVersion = TLSv1_1_MINOR;
5317
            break;
5318
    #endif
5319
0
    #ifndef WOLFSSL_NO_TLS12
5320
0
        case WOLFSSL_TLSV1_2:
5321
0
            *minVersion = TLSv1_2_MINOR;
5322
0
            break;
5323
0
    #endif
5324
0
#endif
5325
0
    #ifdef WOLFSSL_TLS13
5326
0
        case WOLFSSL_TLSV1_3:
5327
0
            *minVersion = TLSv1_3_MINOR;
5328
0
            break;
5329
0
    #endif
5330
5331
#ifdef WOLFSSL_DTLS
5332
        case WOLFSSL_DTLSV1:
5333
            *minVersion = DTLS_MINOR;
5334
            break;
5335
        case WOLFSSL_DTLSV1_2:
5336
            *minVersion = DTLSv1_2_MINOR;
5337
            break;
5338
#ifdef WOLFSSL_DTLS13
5339
        case WOLFSSL_DTLSV1_3:
5340
            *minVersion = DTLSv1_3_MINOR;
5341
            break;
5342
#endif /* WOLFSSL_DTLS13 */
5343
#endif /* WOLFSSL_DTLS */
5344
5345
0
        default:
5346
0
            WOLFSSL_MSG("Bad function argument");
5347
0
            return BAD_FUNC_ARG;
5348
0
    }
5349
5350
0
    return WOLFSSL_SUCCESS;
5351
0
}
5352
5353
5354
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
5355
WOLFSSL_ABI
5356
int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
5357
0
{
5358
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
5359
5360
0
    if (ctx == NULL) {
5361
0
        WOLFSSL_MSG("Bad function argument");
5362
0
        return BAD_FUNC_ARG;
5363
0
    }
5364
5365
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5366
    if (crypto_policy.enabled) {
5367
        return CRYPTO_POLICY_FORBIDDEN;
5368
    }
5369
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5370
5371
0
    return SetMinVersionHelper(&ctx->minDowngrade, version);
5372
0
}
5373
5374
5375
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
5376
int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
5377
0
{
5378
0
    WOLFSSL_ENTER("wolfSSL_SetMinVersion");
5379
5380
0
    if (ssl == NULL) {
5381
0
        WOLFSSL_MSG("Bad function argument");
5382
0
        return BAD_FUNC_ARG;
5383
0
    }
5384
5385
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5386
    if (crypto_policy.enabled) {
5387
        return CRYPTO_POLICY_FORBIDDEN;
5388
    }
5389
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5390
5391
0
    return SetMinVersionHelper(&ssl->options.minDowngrade, version);
5392
0
}
5393
5394
5395
/* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
5396
int wolfSSL_GetVersion(const WOLFSSL* ssl)
5397
0
{
5398
0
    if (ssl == NULL)
5399
0
        return BAD_FUNC_ARG;
5400
5401
0
    if (ssl->version.major == SSLv3_MAJOR) {
5402
0
        switch (ssl->version.minor) {
5403
0
            case SSLv3_MINOR :
5404
0
                return WOLFSSL_SSLV3;
5405
0
            case TLSv1_MINOR :
5406
0
                return WOLFSSL_TLSV1;
5407
0
            case TLSv1_1_MINOR :
5408
0
                return WOLFSSL_TLSV1_1;
5409
0
            case TLSv1_2_MINOR :
5410
0
                return WOLFSSL_TLSV1_2;
5411
0
            case TLSv1_3_MINOR :
5412
0
                return WOLFSSL_TLSV1_3;
5413
0
            default:
5414
0
                break;
5415
0
        }
5416
0
    }
5417
#ifdef WOLFSSL_DTLS
5418
    if (ssl->version.major == DTLS_MAJOR) {
5419
        switch (ssl->version.minor) {
5420
            case DTLS_MINOR :
5421
                return WOLFSSL_DTLSV1;
5422
            case DTLSv1_2_MINOR :
5423
                return WOLFSSL_DTLSV1_2;
5424
            case DTLSv1_3_MINOR :
5425
                return WOLFSSL_DTLSV1_3;
5426
            default:
5427
                break;
5428
        }
5429
    }
5430
#endif /* WOLFSSL_DTLS */
5431
5432
0
    return VERSION_ERROR;
5433
0
}
5434
5435
int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
5436
0
{
5437
0
    word16 haveRSA = 1;
5438
0
    word16 havePSK = 0;
5439
0
    int    keySz   = 0;
5440
5441
0
    WOLFSSL_ENTER("wolfSSL_SetVersion");
5442
5443
0
    if (ssl == NULL) {
5444
0
        WOLFSSL_MSG("Bad function argument");
5445
0
        return BAD_FUNC_ARG;
5446
0
    }
5447
5448
0
    switch (version) {
5449
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
5450
        case WOLFSSL_SSLV3:
5451
            ssl->version = MakeSSLv3();
5452
            break;
5453
#endif
5454
5455
0
#ifndef NO_TLS
5456
    #ifndef NO_OLD_TLS
5457
        #ifdef WOLFSSL_ALLOW_TLSV10
5458
        case WOLFSSL_TLSV1:
5459
            ssl->version = MakeTLSv1();
5460
            break;
5461
        #endif
5462
5463
        case WOLFSSL_TLSV1_1:
5464
            ssl->version = MakeTLSv1_1();
5465
            break;
5466
    #endif
5467
0
    #ifndef WOLFSSL_NO_TLS12
5468
0
        case WOLFSSL_TLSV1_2:
5469
0
            ssl->version = MakeTLSv1_2();
5470
0
            break;
5471
0
    #endif
5472
5473
0
    #ifdef WOLFSSL_TLS13
5474
0
        case WOLFSSL_TLSV1_3:
5475
0
            ssl->version = MakeTLSv1_3();
5476
0
            break;
5477
0
    #endif /* WOLFSSL_TLS13 */
5478
0
#endif
5479
5480
0
        default:
5481
0
            WOLFSSL_MSG("Bad function argument");
5482
0
            return BAD_FUNC_ARG;
5483
0
    }
5484
5485
    #ifdef NO_RSA
5486
        haveRSA = 0;
5487
    #endif
5488
    #ifndef NO_PSK
5489
        havePSK = ssl->options.havePSK;
5490
    #endif
5491
0
    #ifndef NO_CERTS
5492
0
        keySz = ssl->buffers.keySz;
5493
0
    #endif
5494
5495
0
    if (AllocateSuites(ssl) != 0)
5496
0
        return WOLFSSL_FAILURE;
5497
0
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
5498
0
               ssl->options.haveDH, ssl->options.haveECDSAsig,
5499
0
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
5500
0
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
5501
0
    return WOLFSSL_SUCCESS;
5502
0
}
5503
#endif /* !leanpsk */
5504
5505
#ifndef NO_CERTS
5506
5507
/* hash is the SHA digest of name, just use first 32 bits as hash */
5508
static WC_INLINE word32 HashSigner(const byte* hash)
5509
5.56k
{
5510
5.56k
    return MakeWordFromHash(hash) % CA_TABLE_SIZE;
5511
5.56k
}
5512
5513
5514
/* does CA already exist on signer list */
5515
int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash)
5516
3.18k
{
5517
3.18k
    Signer* signers;
5518
3.18k
    int     ret = 0;
5519
3.18k
    word32  row;
5520
5521
3.18k
    if (cm == NULL || hash == NULL) {
5522
0
        return ret;
5523
0
    }
5524
5525
3.18k
    row = HashSigner(hash);
5526
5527
3.18k
    if (wc_LockMutex(&cm->caLock) != 0) {
5528
0
        return ret;
5529
0
    }
5530
3.18k
    signers = cm->caTable[row];
5531
3.81k
    while (signers) {
5532
862
        byte* subjectHash;
5533
5534
862
    #ifndef NO_SKID
5535
862
        subjectHash = signers->subjectKeyIdHash;
5536
    #else
5537
        subjectHash = signers->subjectNameHash;
5538
    #endif
5539
5540
862
        if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
5541
240
            ret = 1; /* success */
5542
240
            break;
5543
240
        }
5544
622
        signers = signers->next;
5545
622
    }
5546
3.18k
    wc_UnLockMutex(&cm->caLock);
5547
5548
3.18k
    return ret;
5549
3.18k
}
5550
5551
5552
#ifdef WOLFSSL_TRUST_PEER_CERT
5553
/* hash is the SHA digest of name, just use first 32 bits as hash */
5554
static WC_INLINE word32 TrustedPeerHashSigner(const byte* hash)
5555
{
5556
    return MakeWordFromHash(hash) % TP_TABLE_SIZE;
5557
}
5558
5559
/* does trusted peer already exist on signer list */
5560
int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert)
5561
{
5562
    TrustedPeerCert* tp;
5563
    int     ret = 0;
5564
    word32  row = TrustedPeerHashSigner(cert->subjectHash);
5565
5566
    if (wc_LockMutex(&cm->tpLock) != 0)
5567
        return  ret;
5568
    tp = cm->tpTable[row];
5569
    while (tp) {
5570
        if ((XMEMCMP(cert->subjectHash, tp->subjectNameHash,
5571
                SIGNER_DIGEST_SIZE) == 0)
5572
    #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER
5573
         && (XMEMCMP(cert->issuerHash, tp->issuerHash,
5574
                SIGNER_DIGEST_SIZE) == 0)
5575
    #endif
5576
        )
5577
            ret = 1;
5578
    #ifndef NO_SKID
5579
        if (cert->extSubjKeyIdSet) {
5580
            /* Compare SKID as well if available */
5581
            if (ret == 1 && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
5582
                    SIGNER_DIGEST_SIZE) != 0)
5583
                ret = 0;
5584
        }
5585
    #endif
5586
        if (ret == 1)
5587
            break;
5588
        tp = tp->next;
5589
    }
5590
    wc_UnLockMutex(&cm->tpLock);
5591
5592
    return ret;
5593
}
5594
5595
5596
/* return Trusted Peer if found, otherwise NULL
5597
    type is what to match on
5598
 */
5599
TrustedPeerCert* GetTrustedPeer(void* vp, DecodedCert* cert)
5600
{
5601
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
5602
    TrustedPeerCert* ret = NULL;
5603
    TrustedPeerCert* tp  = NULL;
5604
    word32  row;
5605
5606
    if (cm == NULL || cert == NULL)
5607
        return NULL;
5608
5609
    row = TrustedPeerHashSigner(cert->subjectHash);
5610
5611
    if (wc_LockMutex(&cm->tpLock) != 0)
5612
        return ret;
5613
5614
    tp = cm->tpTable[row];
5615
    while (tp) {
5616
        if ((XMEMCMP(cert->subjectHash, tp->subjectNameHash,
5617
                SIGNER_DIGEST_SIZE) == 0)
5618
        #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER
5619
             && (XMEMCMP(cert->issuerHash, tp->issuerHash,
5620
                SIGNER_DIGEST_SIZE) == 0)
5621
        #endif
5622
            )
5623
            ret = tp;
5624
    #ifndef NO_SKID
5625
        if (cert->extSubjKeyIdSet) {
5626
            /* Compare SKID as well if available */
5627
            if (ret != NULL && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
5628
                    SIGNER_DIGEST_SIZE) != 0)
5629
                ret = NULL;
5630
        }
5631
    #endif
5632
        if (ret != NULL)
5633
            break;
5634
        tp = tp->next;
5635
    }
5636
    wc_UnLockMutex(&cm->tpLock);
5637
5638
    return ret;
5639
}
5640
5641
5642
int MatchTrustedPeer(TrustedPeerCert* tp, DecodedCert* cert)
5643
{
5644
    if (tp == NULL || cert == NULL)
5645
        return BAD_FUNC_ARG;
5646
5647
    /* subject key id or subject hash has been compared when searching
5648
       tpTable for the cert from function GetTrustedPeer */
5649
5650
    /* compare signatures */
5651
    if (tp->sigLen == cert->sigLength) {
5652
        if (XMEMCMP(tp->sig, cert->signature, cert->sigLength)) {
5653
            return WOLFSSL_FAILURE;
5654
        }
5655
    }
5656
    else {
5657
        return WOLFSSL_FAILURE;
5658
    }
5659
5660
    return WOLFSSL_SUCCESS;
5661
}
5662
#endif /* WOLFSSL_TRUST_PEER_CERT */
5663
5664
5665
/* return CA if found, otherwise NULL */
5666
Signer* GetCA(void* vp, byte* hash)
5667
2.02k
{
5668
2.02k
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
5669
2.02k
    Signer* ret = NULL;
5670
2.02k
    Signer* signers;
5671
2.02k
    word32  row = 0;
5672
5673
2.02k
    if (cm == NULL || hash == NULL)
5674
87
        return NULL;
5675
5676
1.94k
    row = HashSigner(hash);
5677
5678
1.94k
    if (wc_LockMutex(&cm->caLock) != 0)
5679
0
        return ret;
5680
5681
1.94k
    signers = cm->caTable[row];
5682
2.88k
    while (signers) {
5683
1.16k
        byte* subjectHash;
5684
1.16k
        #ifndef NO_SKID
5685
1.16k
            subjectHash = signers->subjectKeyIdHash;
5686
        #else
5687
            subjectHash = signers->subjectNameHash;
5688
        #endif
5689
1.16k
        if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
5690
218
            ret = signers;
5691
218
            break;
5692
218
        }
5693
946
        signers = signers->next;
5694
946
    }
5695
1.94k
    wc_UnLockMutex(&cm->caLock);
5696
5697
1.94k
    return ret;
5698
1.94k
}
5699
5700
#if defined(HAVE_OCSP)
5701
Signer* GetCAByKeyHash(void* vp, const byte* keyHash)
5702
{
5703
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
5704
    Signer* ret = NULL;
5705
    Signer* signers;
5706
    int row;
5707
5708
    if (cm == NULL || keyHash == NULL)
5709
        return NULL;
5710
5711
    /* try lookup using keyHash as subjKeyID first */
5712
    ret = GetCA(vp, (byte*)keyHash);
5713
    if (ret != NULL && XMEMCMP(ret->subjectKeyHash, keyHash, KEYID_SIZE) == 0) {
5714
        return ret;
5715
    }
5716
5717
    /* if we can't find the cert, we have to scan the full table */
5718
    if (wc_LockMutex(&cm->caLock) != 0)
5719
        return NULL;
5720
5721
    /* Unfortunately we need to look through the entire table */
5722
    for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) {
5723
        for (signers = cm->caTable[row]; signers != NULL;
5724
                signers = signers->next) {
5725
            if (XMEMCMP(signers->subjectKeyHash, keyHash, KEYID_SIZE) == 0) {
5726
                ret = signers;
5727
                break;
5728
            }
5729
        }
5730
    }
5731
5732
    wc_UnLockMutex(&cm->caLock);
5733
    return ret;
5734
}
5735
#endif
5736
#ifdef WOLFSSL_AKID_NAME
5737
Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
5738
        const byte* serial, word32 serialSz)
5739
{
5740
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
5741
    Signer* ret = NULL;
5742
    Signer* signers;
5743
    byte nameHash[SIGNER_DIGEST_SIZE];
5744
    byte serialHash[SIGNER_DIGEST_SIZE];
5745
    word32 row;
5746
5747
    if (cm == NULL || issuer == NULL || issuerSz == 0 ||
5748
            serial == NULL || serialSz == 0)
5749
        return NULL;
5750
5751
    if (CalcHashId(issuer, issuerSz, nameHash) != 0 ||
5752
            CalcHashId(serial, serialSz, serialHash) != 0)
5753
        return NULL;
5754
5755
    if (wc_LockMutex(&cm->caLock) != 0)
5756
        return ret;
5757
5758
    /* Unfortunately we need to look through the entire table */
5759
    for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) {
5760
        for (signers = cm->caTable[row]; signers != NULL;
5761
                signers = signers->next) {
5762
            if (XMEMCMP(signers->issuerNameHash, nameHash, SIGNER_DIGEST_SIZE)
5763
                    == 0 && XMEMCMP(signers->serialHash, serialHash,
5764
                                    SIGNER_DIGEST_SIZE) == 0) {
5765
                ret = signers;
5766
                break;
5767
            }
5768
        }
5769
    }
5770
5771
    wc_UnLockMutex(&cm->caLock);
5772
5773
    return ret;
5774
}
5775
#endif
5776
5777
#ifndef NO_SKID
5778
/* return CA if found, otherwise NULL. Walk through hash table. */
5779
Signer* GetCAByName(void* vp, byte* hash)
5780
5.17k
{
5781
5.17k
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
5782
5.17k
    Signer* ret = NULL;
5783
5.17k
    Signer* signers;
5784
5.17k
    word32  row;
5785
5786
5.17k
    if (cm == NULL)
5787
1.62k
        return NULL;
5788
5789
3.54k
    if (wc_LockMutex(&cm->caLock) != 0)
5790
0
        return ret;
5791
5792
41.9k
    for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) {
5793
38.4k
        signers = cm->caTable[row];
5794
40.0k
        while (signers && ret == NULL) {
5795
1.62k
            if (XMEMCMP(hash, signers->subjectNameHash,
5796
1.62k
                        SIGNER_DIGEST_SIZE) == 0) {
5797
92
                ret = signers;
5798
92
            }
5799
1.62k
            signers = signers->next;
5800
1.62k
        }
5801
38.4k
    }
5802
3.54k
    wc_UnLockMutex(&cm->caLock);
5803
5804
3.54k
    return ret;
5805
3.54k
}
5806
#endif
5807
5808
5809
#ifdef WOLFSSL_TRUST_PEER_CERT
5810
/* add a trusted peer cert to linked list */
5811
int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify)
5812
{
5813
    int ret = 0;
5814
    int row = 0;
5815
    TrustedPeerCert* peerCert;
5816
    DecodedCert* cert;
5817
    DerBuffer*   der = *pDer;
5818
5819
    WOLFSSL_MSG("Adding a Trusted Peer Cert");
5820
5821
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cm->heap,
5822
                                 DYNAMIC_TYPE_DCERT);
5823
    if (cert == NULL) {
5824
        FreeDer(&der);
5825
        return MEMORY_E;
5826
    }
5827
5828
    InitDecodedCert(cert, der->buffer, der->length, cm->heap);
5829
    if ((ret = ParseCert(cert, TRUSTED_PEER_TYPE, verify, cm)) != 0) {
5830
        FreeDecodedCert(cert);
5831
        XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
5832
        FreeDer(&der);
5833
        return ret;
5834
    }
5835
    WOLFSSL_MSG("\tParsed new trusted peer cert");
5836
5837
    peerCert = (TrustedPeerCert*)XMALLOC(sizeof(TrustedPeerCert), cm->heap,
5838
                                                             DYNAMIC_TYPE_CERT);
5839
    if (peerCert == NULL) {
5840
        FreeDecodedCert(cert);
5841
        XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5842
        FreeDer(&der);
5843
        return MEMORY_E;
5844
    }
5845
    XMEMSET(peerCert, 0, sizeof(TrustedPeerCert));
5846
5847
    #ifndef IGNORE_NAME_CONSTRAINTS
5848
        if (peerCert->permittedNames)
5849
            FreeNameSubtrees(peerCert->permittedNames, cm->heap);
5850
        if (peerCert->excludedNames)
5851
            FreeNameSubtrees(peerCert->excludedNames, cm->heap);
5852
    #endif
5853
5854
    if (AlreadyTrustedPeer(cm, cert)) {
5855
        WOLFSSL_MSG("\tAlready have this CA, not adding again");
5856
        FreeTrustedPeer(peerCert, cm->heap);
5857
        (void)ret;
5858
    }
5859
    else {
5860
        /* add trusted peer signature */
5861
        peerCert->sigLen = cert->sigLength;
5862
        peerCert->sig = (byte *)XMALLOC(cert->sigLength, cm->heap,
5863
                                                        DYNAMIC_TYPE_SIGNATURE);
5864
        if (peerCert->sig == NULL) {
5865
            FreeDecodedCert(cert);
5866
            XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5867
            FreeTrustedPeer(peerCert, cm->heap);
5868
            FreeDer(&der);
5869
            return MEMORY_E;
5870
        }
5871
        XMEMCPY(peerCert->sig, cert->signature, cert->sigLength);
5872
5873
        /* add trusted peer name */
5874
        peerCert->nameLen = cert->subjectCNLen;
5875
        peerCert->name    = cert->subjectCN;
5876
        #ifndef IGNORE_NAME_CONSTRAINTS
5877
            peerCert->permittedNames = cert->permittedNames;
5878
            peerCert->excludedNames  = cert->excludedNames;
5879
        #endif
5880
5881
        /* add SKID when available and hash of name */
5882
        #ifndef NO_SKID
5883
            XMEMCPY(peerCert->subjectKeyIdHash, cert->extSubjKeyId,
5884
                    SIGNER_DIGEST_SIZE);
5885
        #endif
5886
            XMEMCPY(peerCert->subjectNameHash, cert->subjectHash,
5887
                    SIGNER_DIGEST_SIZE);
5888
        #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER
5889
            XMEMCPY(peerCert->issuerHash, cert->issuerHash,
5890
                    SIGNER_DIGEST_SIZE);
5891
        #endif
5892
            /* If Key Usage not set, all uses valid. */
5893
            peerCert->next    = NULL;
5894
            cert->subjectCN = 0;
5895
        #ifndef IGNORE_NAME_CONSTRAINTS
5896
            cert->permittedNames = NULL;
5897
            cert->excludedNames = NULL;
5898
        #endif
5899
5900
            row = (int)TrustedPeerHashSigner(peerCert->subjectNameHash);
5901
5902
            if (wc_LockMutex(&cm->tpLock) == 0) {
5903
                peerCert->next = cm->tpTable[row];
5904
                cm->tpTable[row] = peerCert;   /* takes ownership */
5905
                wc_UnLockMutex(&cm->tpLock);
5906
            }
5907
            else {
5908
                WOLFSSL_MSG("\tTrusted Peer Cert Mutex Lock failed");
5909
                FreeDecodedCert(cert);
5910
                XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5911
                FreeTrustedPeer(peerCert, cm->heap);
5912
                FreeDer(&der);
5913
                return BAD_MUTEX_E;
5914
            }
5915
        }
5916
5917
    WOLFSSL_MSG("\tFreeing parsed trusted peer cert");
5918
    FreeDecodedCert(cert);
5919
    XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5920
    WOLFSSL_MSG("\tFreeing der trusted peer cert");
5921
    FreeDer(&der);
5922
    WOLFSSL_MSG("\t\tOK Freeing der trusted peer cert");
5923
    WOLFSSL_LEAVE("AddTrustedPeer", ret);
5924
5925
    return WOLFSSL_SUCCESS;
5926
}
5927
#endif /* WOLFSSL_TRUST_PEER_CERT */
5928
5929
int AddSigner(WOLFSSL_CERT_MANAGER* cm, Signer *s)
5930
0
{
5931
0
    byte*   subjectHash;
5932
0
    Signer* signers;
5933
0
    word32  row;
5934
5935
0
    if (cm == NULL || s == NULL)
5936
0
        return BAD_FUNC_ARG;
5937
5938
0
#ifndef NO_SKID
5939
0
    subjectHash = s->subjectKeyIdHash;
5940
#else
5941
    subjectHash = s->subjectNameHash;
5942
#endif
5943
5944
0
    if (AlreadySigner(cm, subjectHash)) {
5945
0
        FreeSigner(s, cm->heap);
5946
0
        return 0;
5947
0
    }
5948
5949
0
    row = HashSigner(subjectHash);
5950
5951
0
    if (wc_LockMutex(&cm->caLock) != 0)
5952
0
        return BAD_MUTEX_E;
5953
5954
0
    signers = cm->caTable[row];
5955
0
    s->next = signers;
5956
0
    cm->caTable[row] = s;
5957
5958
0
    wc_UnLockMutex(&cm->caLock);
5959
0
    return 0;
5960
0
}
5961
5962
/* owns der, internal now uses too */
5963
/* type flag ids from user or from chain received during verify
5964
   don't allow chain ones to be added w/o isCA extension */
5965
int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify)
5966
0
{
5967
0
    int         ret;
5968
0
    Signer*     signer = NULL;
5969
0
    word32      row;
5970
0
    byte*       subjectHash;
5971
0
    WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
5972
0
    DerBuffer*   der = *pDer;
5973
5974
0
    WOLFSSL_MSG_CERT_LOG("Adding a CA");
5975
5976
0
    if (cm == NULL) {
5977
0
        FreeDer(pDer);
5978
0
        return BAD_FUNC_ARG;
5979
0
    }
5980
5981
0
    #ifdef WOLFSSL_SMALL_STACK
5982
0
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT);
5983
0
    if (cert == NULL) {
5984
0
        FreeDer(pDer);
5985
0
        return MEMORY_E;
5986
0
    }
5987
0
    #endif
5988
5989
0
    InitDecodedCert(cert, der->buffer, der->length, cm->heap);
5990
5991
#ifdef WC_ASN_UNKNOWN_EXT_CB
5992
    if (cm->unknownExtCallback != NULL) {
5993
        wc_SetUnknownExtCallback(cert, cm->unknownExtCallback);
5994
    }
5995
#endif
5996
5997
0
    WOLFSSL_MSG_CERT("\tParsing new CA");
5998
0
    ret = ParseCert(cert, CA_TYPE, verify, cm);
5999
6000
0
    WOLFSSL_MSG("\tParsed new CA");
6001
#ifdef WOLFSSL_DEBUG_CERTS
6002
    {
6003
        const char*  err_msg;
6004
        if (ret == 0) {
6005
            WOLFSSL_MSG_CERT_EX(WOLFSSL_MSG_CERT_INDENT "issuer:  '%s'",
6006
                cert->issuer);
6007
            WOLFSSL_MSG_CERT_EX(WOLFSSL_MSG_CERT_INDENT "subject: '%s'",
6008
                cert->subject);
6009
        }
6010
        else {
6011
            WOLFSSL_MSG_CERT(
6012
                WOLFSSL_MSG_CERT_INDENT "Failed during parse of new CA");
6013
            err_msg = wc_GetErrorString(ret);
6014
            WOLFSSL_MSG_CERT_EX(WOLFSSL_MSG_CERT_INDENT "error ret: %d; %s",
6015
                ret, err_msg);
6016
        }
6017
    }
6018
#endif /* WOLFSSL_DEBUG_CERTS */
6019
6020
0
#ifndef NO_SKID
6021
0
    subjectHash = cert->extSubjKeyId;
6022
#else
6023
    subjectHash = cert->subjectHash;
6024
#endif
6025
6026
    /* check CA key size */
6027
0
    if (verify && (ret == 0 )) {
6028
0
        switch (cert->keyOID) {
6029
0
        #ifndef NO_RSA
6030
0
            #ifdef WC_RSA_PSS
6031
0
            case RSAPSSk:
6032
0
            #endif
6033
0
            case RSAk:
6034
0
                if (cm->minRsaKeySz < 0 ||
6035
0
                                   cert->pubKeySize < (word16)cm->minRsaKeySz) {
6036
0
                    ret = RSA_KEY_SIZE_E;
6037
0
                    WOLFSSL_MSG_CERT_LOG("\tCA RSA key size error");
6038
0
                    WOLFSSL_MSG_CERT_EX("\tCA RSA pubKeySize = %d; "
6039
0
                                                "minRsaKeySz = %d",
6040
0
                                   cert->pubKeySize, cm->minRsaKeySz);
6041
0
                }
6042
0
                break;
6043
0
        #endif /* !NO_RSA */
6044
0
            #ifdef HAVE_ECC
6045
0
            case ECDSAk:
6046
0
                if (cm->minEccKeySz < 0 ||
6047
0
                                   cert->pubKeySize < (word16)cm->minEccKeySz) {
6048
0
                    ret = ECC_KEY_SIZE_E;
6049
0
                    WOLFSSL_MSG_CERT_LOG("\tCA ECC key size error");
6050
0
                    WOLFSSL_MSG_CERT_EX("\tCA ECC pubKeySize = %d; "
6051
0
                                                 "minEccKeySz = %d",
6052
0
                                   cert->pubKeySize, cm->minEccKeySz);
6053
0
                }
6054
0
                break;
6055
0
            #endif /* HAVE_ECC */
6056
0
            #ifdef HAVE_ED25519
6057
0
            case ED25519k:
6058
0
                if (cm->minEccKeySz < 0 ||
6059
0
                                   ED25519_KEY_SIZE < (word16)cm->minEccKeySz) {
6060
0
                    ret = ECC_KEY_SIZE_E;
6061
0
                    WOLFSSL_MSG("\tCA ECC key size error");
6062
0
                }
6063
0
                break;
6064
0
            #endif /* HAVE_ED25519 */
6065
0
            #ifdef HAVE_ED448
6066
0
            case ED448k:
6067
0
                if (cm->minEccKeySz < 0 ||
6068
0
                                     ED448_KEY_SIZE < (word16)cm->minEccKeySz) {
6069
0
                    ret = ECC_KEY_SIZE_E;
6070
0
                    WOLFSSL_MSG("\tCA ECC key size error");
6071
0
                }
6072
0
                break;
6073
0
            #endif /* HAVE_ED448 */
6074
            #if defined(HAVE_FALCON)
6075
            case FALCON_LEVEL1k:
6076
                if (cm->minFalconKeySz < 0 ||
6077
                          FALCON_LEVEL1_KEY_SIZE < (word16)cm->minFalconKeySz) {
6078
                    ret = FALCON_KEY_SIZE_E;
6079
                    WOLFSSL_MSG("\tCA Falcon level 1 key size error");
6080
                }
6081
                break;
6082
            case FALCON_LEVEL5k:
6083
                if (cm->minFalconKeySz < 0 ||
6084
                          FALCON_LEVEL5_KEY_SIZE < (word16)cm->minFalconKeySz) {
6085
                    ret = FALCON_KEY_SIZE_E;
6086
                    WOLFSSL_MSG("\tCA Falcon level 5 key size error");
6087
                }
6088
                break;
6089
            #endif /* HAVE_FALCON */
6090
            #if defined(HAVE_DILITHIUM)
6091
            #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
6092
            case DILITHIUM_LEVEL2k:
6093
                if (cm->minDilithiumKeySz < 0 ||
6094
                    DILITHIUM_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6095
                    ret = DILITHIUM_KEY_SIZE_E;
6096
                    WOLFSSL_MSG("\tCA Dilithium level 2 key size error");
6097
                }
6098
                break;
6099
            case DILITHIUM_LEVEL3k:
6100
                if (cm->minDilithiumKeySz < 0 ||
6101
                    DILITHIUM_LEVEL3_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6102
                    ret = DILITHIUM_KEY_SIZE_E;
6103
                    WOLFSSL_MSG("\tCA Dilithium level 3 key size error");
6104
                }
6105
                break;
6106
            case DILITHIUM_LEVEL5k:
6107
                if (cm->minDilithiumKeySz < 0 ||
6108
                    DILITHIUM_LEVEL5_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6109
                    ret = DILITHIUM_KEY_SIZE_E;
6110
                    WOLFSSL_MSG("\tCA Dilithium level 5 key size error");
6111
                }
6112
                break;
6113
            #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
6114
            case ML_DSA_LEVEL2k:
6115
                if (cm->minDilithiumKeySz < 0 ||
6116
                    ML_DSA_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6117
                    ret = DILITHIUM_KEY_SIZE_E;
6118
                    WOLFSSL_MSG("\tCA Dilithium level 2 key size error");
6119
                }
6120
                break;
6121
            case ML_DSA_LEVEL3k:
6122
                if (cm->minDilithiumKeySz < 0 ||
6123
                    ML_DSA_LEVEL3_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6124
                    ret = DILITHIUM_KEY_SIZE_E;
6125
                    WOLFSSL_MSG("\tCA Dilithium level 3 key size error");
6126
                }
6127
                break;
6128
            case ML_DSA_LEVEL5k:
6129
                if (cm->minDilithiumKeySz < 0 ||
6130
                    ML_DSA_LEVEL5_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
6131
                    ret = DILITHIUM_KEY_SIZE_E;
6132
                    WOLFSSL_MSG("\tCA Dilithium level 5 key size error");
6133
                }
6134
                break;
6135
            #endif /* HAVE_DILITHIUM */
6136
6137
0
            default:
6138
0
                WOLFSSL_MSG("\tNo key size check done on CA");
6139
0
                break; /* no size check if key type is not in switch */
6140
0
        }
6141
0
    }
6142
6143
0
    if (ret == 0 && cert->isCA == 0 && type != WOLFSSL_USER_CA &&
6144
0
        type != WOLFSSL_TEMP_CA) {
6145
0
        WOLFSSL_MSG("\tCan't add as CA if not actually one");
6146
0
        ret = NOT_CA_ERROR;
6147
0
    }
6148
0
#ifndef ALLOW_INVALID_CERTSIGN
6149
0
    else if (ret == 0 && cert->isCA == 1 && type != WOLFSSL_USER_CA &&
6150
0
        type != WOLFSSL_TEMP_CA && !cert->selfSigned &&
6151
0
        (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0) {
6152
        /* Intermediate CA certs are required to have the keyCertSign
6153
        * extension set. User loaded root certs are not. */
6154
0
        WOLFSSL_MSG("\tDoesn't have key usage certificate signing");
6155
0
        ret = NOT_CA_ERROR;
6156
0
    }
6157
0
#endif
6158
0
    else if (ret == 0 && AlreadySigner(cm, subjectHash)) {
6159
0
        WOLFSSL_MSG("\tAlready have this CA, not adding again");
6160
0
        (void)ret;
6161
0
    }
6162
0
    else if (ret == 0) {
6163
        /* take over signer parts */
6164
0
        signer = MakeSigner(cm->heap);
6165
0
        if (!signer)
6166
0
            ret = MEMORY_ERROR;
6167
0
    }
6168
0
    if (ret == 0 && signer != NULL) {
6169
0
        ret = FillSigner(signer, cert, type, der);
6170
6171
0
        if (ret == 0){
6172
0
        #ifndef NO_SKID
6173
0
            row = HashSigner(signer->subjectKeyIdHash);
6174
        #else
6175
            row = HashSigner(signer->subjectNameHash);
6176
        #endif
6177
0
        }
6178
6179
    #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
6180
        /* Verify CA by TSIP so that generated tsip key is going to          */
6181
        /* be able to be used for peer's cert verification                   */
6182
        /* TSIP is only able to handle USER CA, and only one CA.             */
6183
        /* Therefore, it doesn't need to call TSIP again if there is already */
6184
        /* verified CA.                                                      */
6185
        if ( ret == 0 && signer != NULL ) {
6186
            signer->cm_idx = row;
6187
            if (type == WOLFSSL_USER_CA) {
6188
                if ((ret = wc_Renesas_cmn_RootCertVerify(cert->source,
6189
                        cert->maxIdx,
6190
                        cert->sigCtx.CertAtt.pubkey_n_start,
6191
                        cert->sigCtx.CertAtt.pubkey_n_len - 1,
6192
                        cert->sigCtx.CertAtt.pubkey_e_start,
6193
                        cert->sigCtx.CertAtt.pubkey_e_len - 1,
6194
                     row/* cm index */))
6195
                    < 0)
6196
                    WOLFSSL_MSG("Renesas_RootCertVerify() failed");
6197
                else
6198
                    WOLFSSL_MSG("Renesas_RootCertVerify() succeed or skipped");
6199
            }
6200
        }
6201
    #endif /* TSIP or SCE */
6202
6203
0
        if (ret == 0 && wc_LockMutex(&cm->caLock) == 0) {
6204
0
            signer->next = cm->caTable[row];
6205
0
            cm->caTable[row] = signer;   /* takes ownership */
6206
0
            wc_UnLockMutex(&cm->caLock);
6207
0
            if (cm->caCacheCallback)
6208
0
                cm->caCacheCallback(der->buffer, (int)der->length, type);
6209
0
        }
6210
0
        else {
6211
0
            WOLFSSL_MSG("\tCA Mutex Lock failed");
6212
0
            ret = BAD_MUTEX_E;
6213
0
        }
6214
0
    }
6215
6216
0
    WOLFSSL_MSG("\tFreeing Parsed CA");
6217
0
    FreeDecodedCert(cert);
6218
0
    if (ret != 0 && signer != NULL)
6219
0
        FreeSigner(signer, cm->heap);
6220
0
    WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
6221
0
    WOLFSSL_MSG("\tFreeing der CA");
6222
0
    FreeDer(pDer);
6223
0
    WOLFSSL_MSG("\t\tOK Freeing der CA");
6224
6225
0
    WOLFSSL_LEAVE("AddCA", ret);
6226
6227
0
    return ret == 0 ? WOLFSSL_SUCCESS : ret;
6228
0
}
6229
6230
/* Removes the CA with the passed in subject hash from the
6231
   cert manager's CA cert store. */
6232
int RemoveCA(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type)
6233
0
{
6234
0
    Signer* current;
6235
0
    Signer** prev;
6236
0
    int     ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
6237
0
    word32  row;
6238
6239
0
    WOLFSSL_MSG("Removing a CA");
6240
6241
0
    if (cm == NULL || hash == NULL) {
6242
0
        return BAD_FUNC_ARG;
6243
0
    }
6244
6245
0
    row = HashSigner(hash);
6246
6247
0
    if (wc_LockMutex(&cm->caLock) != 0) {
6248
0
        return BAD_MUTEX_E;
6249
0
    }
6250
0
    current = cm->caTable[row];
6251
0
    prev = &cm->caTable[row];
6252
0
    while (current) {
6253
0
        byte* subjectHash;
6254
6255
0
    #ifndef NO_SKID
6256
0
        subjectHash = current->subjectKeyIdHash;
6257
    #else
6258
        subjectHash = current->subjectNameHash;
6259
    #endif
6260
6261
0
        if ((current->type == type) &&
6262
0
            (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0)) {
6263
0
            *prev = current->next;
6264
0
            FreeSigner(current, cm->heap);
6265
0
            ret = WOLFSSL_SUCCESS;
6266
0
            break;
6267
0
        }
6268
0
        prev = &current->next;
6269
0
        current = current->next;
6270
0
    }
6271
0
    wc_UnLockMutex(&cm->caLock);
6272
6273
0
    WOLFSSL_LEAVE("RemoveCA", ret);
6274
6275
0
    return ret;
6276
0
}
6277
6278
6279
/* Sets the CA with the passed in subject hash
6280
   to the provided type. */
6281
int SetCAType(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type)
6282
0
{
6283
0
    Signer* current;
6284
0
    int     ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
6285
0
    word32  row;
6286
6287
0
    WOLFSSL_MSG_EX("Setting CA to type %d", type);
6288
6289
0
    if (cm == NULL || hash == NULL ||
6290
0
        type < WOLFSSL_USER_CA || type > WOLFSSL_USER_INTER) {
6291
0
        return ret;
6292
0
    }
6293
6294
0
    row = HashSigner(hash);
6295
6296
0
    if (wc_LockMutex(&cm->caLock) != 0) {
6297
0
        return ret;
6298
0
    }
6299
0
    current = cm->caTable[row];
6300
0
    while (current) {
6301
0
        byte* subjectHash;
6302
6303
0
    #ifndef NO_SKID
6304
0
        subjectHash = current->subjectKeyIdHash;
6305
    #else
6306
        subjectHash = current->subjectNameHash;
6307
    #endif
6308
6309
0
        if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
6310
0
            current->type = (byte)type;
6311
0
            ret = WOLFSSL_SUCCESS;
6312
0
            break;
6313
0
        }
6314
0
        current = current->next;
6315
0
    }
6316
0
    wc_UnLockMutex(&cm->caLock);
6317
6318
0
    WOLFSSL_LEAVE("SetCAType", ret);
6319
6320
0
    return ret;
6321
0
}
6322
#endif /* !NO_CERTS */
6323
6324
6325
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
6326
static int wolfSSL_RAND_InitMutex(void);
6327
#endif
6328
6329
/* If we don't have static mutex initializers, but we do have static atomic
6330
 * initializers, activate WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS to leverage
6331
 * the latter.
6332
 *
6333
 * See further explanation below in wolfSSL_Init().
6334
 */
6335
#ifndef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6336
    #if !defined(WOLFSSL_MUTEX_INITIALIZER) && !defined(SINGLE_THREADED) && \
6337
            defined(WOLFSSL_ATOMIC_OPS) && defined(WOLFSSL_ATOMIC_INITIALIZER)
6338
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 1
6339
    #else
6340
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
6341
    #endif
6342
#elif defined(WOLFSSL_MUTEX_INITIALIZER) || defined(SINGLE_THREADED)
6343
    #undef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6344
    #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
6345
#endif
6346
6347
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6348
    #ifndef WOLFSSL_ATOMIC_OPS
6349
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_OPS
6350
    #endif
6351
    #ifndef WOLFSSL_ATOMIC_INITIALIZER
6352
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_INITIALIZER
6353
    #endif
6354
    static wolfSSL_Atomic_Int inits_count_mutex_atomic_initing_flag =
6355
        WOLFSSL_ATOMIC_INITIALIZER(0);
6356
#endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS && !WOLFSSL_MUTEX_INITIALIZER */
6357
6358
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
6359
static void AtExitCleanup(void)
6360
{
6361
    if (initRefCount > 0) {
6362
        initRefCount = 1;
6363
        (void)wolfSSL_Cleanup();
6364
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6365
        if (inits_count_mutex_valid == 1) {
6366
            (void)wc_FreeMutex(&inits_count_mutex);
6367
            inits_count_mutex_valid = 0;
6368
            inits_count_mutex_atomic_initing_flag = 0;
6369
        }
6370
#endif
6371
    }
6372
}
6373
#endif
6374
6375
WOLFSSL_ABI
6376
int wolfSSL_Init(void)
6377
4.85k
{
6378
4.85k
    int ret = WOLFSSL_SUCCESS;
6379
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
6380
    int i;
6381
#endif
6382
6383
4.85k
    WOLFSSL_ENTER("wolfSSL_Init");
6384
6385
4.85k
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
6386
4.85k
    WOLFSSL_MSG(LIBWOLFSSL_CMAKE_OUTPUT);
6387
#else
6388
    WOLFSSL_MSG("No extra wolfSSL cmake messages found");
6389
#endif
6390
6391
#ifndef WOLFSSL_MUTEX_INITIALIZER
6392
    if (inits_count_mutex_valid == 0) {
6393
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6394
6395
        /* Without this mitigation, if two threads enter wolfSSL_Init() at the
6396
         * same time, and both see zero inits_count_mutex_valid, then both will
6397
         * run wc_InitMutex(&inits_count_mutex), leading to process corruption
6398
         * or (best case) a resource leak.
6399
         *
6400
         * When WOLFSSL_ATOMIC_INITIALIZER() is available, we can mitigate this
6401
         * by use an atomic counting int as a mutex.
6402
         */
6403
6404
        if (wolfSSL_Atomic_Int_FetchAdd(&inits_count_mutex_atomic_initing_flag,
6405
                                        1) != 0)
6406
        {
6407
            (void)wolfSSL_Atomic_Int_FetchSub(
6408
                &inits_count_mutex_atomic_initing_flag, 1);
6409
            return DEADLOCK_AVERTED_E;
6410
        }
6411
    #endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS */
6412
        if (wc_InitMutex(&inits_count_mutex) != 0) {
6413
            WOLFSSL_MSG("Bad Init Mutex count");
6414
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
6415
            (void)wolfSSL_Atomic_Int_FetchSub(
6416
                &inits_count_mutex_atomic_initing_flag, 1);
6417
    #endif
6418
            return BAD_MUTEX_E;
6419
        }
6420
        else {
6421
            inits_count_mutex_valid = 1;
6422
        }
6423
    }
6424
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
6425
6426
4.85k
    if (wc_LockMutex(&inits_count_mutex) != 0) {
6427
0
        WOLFSSL_MSG("Bad Lock Mutex count");
6428
0
        return BAD_MUTEX_E;
6429
0
    }
6430
6431
#if FIPS_VERSION_GE(5,1)
6432
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
6433
        ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL);
6434
        if (ret == 0)
6435
            ret = WOLFSSL_SUCCESS;
6436
    }
6437
#endif
6438
6439
4.85k
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
6440
        /* Initialize crypto for use with TLS connection */
6441
6442
4.85k
        if (wolfCrypt_Init() != 0) {
6443
0
            WOLFSSL_MSG("Bad wolfCrypt Init");
6444
0
            ret = WC_INIT_E;
6445
0
        }
6446
6447
#if defined(HAVE_GLOBAL_RNG) && !defined(WOLFSSL_MUTEX_INITIALIZER)
6448
        if (ret == WOLFSSL_SUCCESS) {
6449
            if (wc_InitMutex(&globalRNGMutex) != 0) {
6450
                WOLFSSL_MSG("Bad Init Mutex rng");
6451
                ret = BAD_MUTEX_E;
6452
            }
6453
            else {
6454
                globalRNGMutex_valid = 1;
6455
            }
6456
        }
6457
#endif
6458
6459
    #ifdef WC_RNG_SEED_CB
6460
        wc_SetSeed_Cb(WC_GENERATE_SEED_DEFAULT);
6461
    #endif
6462
6463
#ifdef OPENSSL_EXTRA
6464
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
6465
        if ((ret == WOLFSSL_SUCCESS) && (wolfSSL_RAND_InitMutex() != 0)) {
6466
            ret = BAD_MUTEX_E;
6467
        }
6468
    #endif
6469
        if ((ret == WOLFSSL_SUCCESS) &&
6470
            (wolfSSL_RAND_seed(NULL, 0) != WOLFSSL_SUCCESS)) {
6471
            WOLFSSL_MSG("wolfSSL_RAND_seed failed");
6472
            ret = WC_INIT_E;
6473
        }
6474
#endif
6475
6476
4.85k
#ifndef NO_SESSION_CACHE
6477
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
6478
        for (i = 0; i < SESSION_ROWS; ++i) {
6479
            SessionCache[i].lock_valid = 0;
6480
        }
6481
        for (i = 0; (ret == WOLFSSL_SUCCESS) && (i < SESSION_ROWS); ++i) {
6482
            if (wc_InitRwLock(&SessionCache[i].row_lock) != 0) {
6483
                WOLFSSL_MSG("Bad Init Mutex session");
6484
                ret = BAD_MUTEX_E;
6485
            }
6486
            else {
6487
                SessionCache[i].lock_valid = 1;
6488
            }
6489
        }
6490
    #else
6491
4.85k
        if (ret == WOLFSSL_SUCCESS) {
6492
4.85k
            if (wc_InitRwLock(&session_lock) != 0) {
6493
0
                WOLFSSL_MSG("Bad Init Mutex session");
6494
0
                ret = BAD_MUTEX_E;
6495
0
            }
6496
4.85k
            else {
6497
4.85k
                session_lock_valid = 1;
6498
4.85k
            }
6499
4.85k
        }
6500
4.85k
    #endif
6501
4.85k
    #ifndef NO_CLIENT_CACHE
6502
        #ifndef WOLFSSL_MUTEX_INITIALIZER
6503
        if (ret == WOLFSSL_SUCCESS) {
6504
            if (wc_InitMutex(&clisession_mutex) != 0) {
6505
                WOLFSSL_MSG("Bad Init Mutex session");
6506
                ret = BAD_MUTEX_E;
6507
            }
6508
            else {
6509
                clisession_mutex_valid = 1;
6510
            }
6511
        }
6512
        #endif
6513
4.85k
    #endif
6514
4.85k
#endif
6515
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
6516
        /* OpenSSL registers cleanup using atexit */
6517
        if ((ret == WOLFSSL_SUCCESS) && (atexit(AtExitCleanup) != 0)) {
6518
            WOLFSSL_MSG("Bad atexit registration");
6519
            ret = WC_INIT_E;
6520
        }
6521
#endif
6522
4.85k
    }
6523
6524
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
6525
    /* System wide crypto policy disabled by default. */
6526
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
6527
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
6528
6529
4.85k
    if (ret == WOLFSSL_SUCCESS) {
6530
4.85k
        initRefCount++;
6531
4.85k
    }
6532
0
    else {
6533
0
        initRefCount = 1; /* Force cleanup */
6534
0
    }
6535
6536
4.85k
    wc_UnLockMutex(&inits_count_mutex);
6537
6538
4.85k
    if (ret != WOLFSSL_SUCCESS) {
6539
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
6540
0
    }
6541
6542
4.85k
    return ret;
6543
4.85k
}
6544
6545
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
6546
/* Helper function for wolfSSL_crypto_policy_enable and
6547
 * wolfSSL_crypto_policy_enable_buffer.
6548
 *
6549
 * Parses the crypto policy string, verifies values,
6550
 * and sets in global crypto policy struct. Not thread
6551
 * safe. String length has already been verified.
6552
 *
6553
 * Returns WOLFSSL_SUCCESS on success.
6554
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
6555
 * Returns < 0 on misc error.
6556
 * */
6557
static int crypto_policy_parse(void)
6558
{
6559
    const char * hdr = WOLFSSL_SECLEVEL_STR;
6560
    int          sec_level = 0;
6561
    size_t       i = 0;
6562
6563
    /* All policies should begin with "@SECLEVEL=<N>" (N={0..5}) followed
6564
     * by bulk cipher list. */
6565
    if (XMEMCMP(crypto_policy.str, hdr, strlen(hdr)) != 0) {
6566
        WOLFSSL_MSG("error: crypto policy: invalid header");
6567
        return WOLFSSL_BAD_FILE;
6568
    }
6569
6570
    {
6571
        /* Extract the security level. */
6572
        char *       policy_mem = crypto_policy.str;
6573
        policy_mem += strlen(hdr);
6574
        sec_level = (int) (*policy_mem - '0');
6575
    }
6576
6577
    if (sec_level < MIN_WOLFSSL_SEC_LEVEL ||
6578
        sec_level > MAX_WOLFSSL_SEC_LEVEL) {
6579
        WOLFSSL_MSG_EX("error: invalid SECLEVEL: %d", sec_level);
6580
        return WOLFSSL_BAD_FILE;
6581
    }
6582
6583
    /* Remove trailing '\r' or '\n'. */
6584
    for (i = 0; i < MAX_WOLFSSL_CRYPTO_POLICY_SIZE; ++i) {
6585
        if (crypto_policy.str[i] == '\0') {
6586
            break;
6587
        }
6588
6589
        if (crypto_policy.str[i] == '\r' || crypto_policy.str[i] == '\n') {
6590
            crypto_policy.str[i] = '\0';
6591
            break;
6592
        }
6593
    }
6594
6595
    #if defined(DEBUG_WOLFSSL_VERBOSE)
6596
    WOLFSSL_MSG_EX("info: SECLEVEL=%d", sec_level);
6597
    WOLFSSL_MSG_EX("info: using crypto-policy file: %s, %ld", policy_file, sz);
6598
    #endif /* DEBUG_WOLFSSL_VERBOSE */
6599
6600
    crypto_policy.secLevel = sec_level;
6601
    crypto_policy.enabled = 1;
6602
6603
    return WOLFSSL_SUCCESS;
6604
}
6605
6606
#ifndef NO_FILESYSTEM
6607
/* Enables wolfSSL system wide crypto-policy, using the given policy
6608
 * file arg. If NULL is passed, then the default system crypto-policy
6609
 * file that was set at configure time will be used instead.
6610
 *
6611
 * While enabled:
6612
 *   - TLS methods, min key sizes, and cipher lists are all configured
6613
 *     automatically by the policy.
6614
 *   - Attempting to use lesser strength parameters will fail with
6615
 *     error CRYPTO_POLICY_FORBIDDEN.
6616
 *
6617
 * Disable with wolfSSL_crypto_policy_disable.
6618
 *
6619
 * Note: the wolfSSL_crypto_policy_X API are not thread safe, and should
6620
 * only be called at program init time.
6621
 *
6622
 * Returns WOLFSSL_SUCCESS on success.
6623
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
6624
 * Returns < 0 on misc error.
6625
 * */
6626
int wolfSSL_crypto_policy_enable(const char * policy_file)
6627
{
6628
    XFILE   file;
6629
    long    sz = 0;
6630
    size_t  n_read = 0;
6631
6632
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable");
6633
6634
    if (wolfSSL_crypto_policy_is_enabled()) {
6635
        WOLFSSL_MSG_EX("error: crypto policy already enabled: %s",
6636
                       policy_file);
6637
        return CRYPTO_POLICY_FORBIDDEN;
6638
    }
6639
6640
    if (policy_file == NULL) {
6641
        /* Use the configure-time default if NULL passed. */
6642
        policy_file = WC_STRINGIFY(WOLFSSL_CRYPTO_POLICY_FILE);
6643
    }
6644
6645
    if (policy_file == NULL || *policy_file == '\0') {
6646
        WOLFSSL_MSG("error: crypto policy empty file");
6647
        return BAD_FUNC_ARG;
6648
    }
6649
6650
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
6651
6652
    file = XFOPEN(policy_file, "rb");
6653
6654
    if (file == XBADFILE) {
6655
        WOLFSSL_MSG_EX("error: crypto policy file open failed: %s",
6656
                       policy_file);
6657
        return WOLFSSL_BAD_FILE;
6658
    }
6659
6660
    if (XFSEEK(file, 0, XSEEK_END) != 0) {
6661
        WOLFSSL_MSG_EX("error: crypto policy file seek end failed: %s",
6662
                       policy_file);
6663
        XFCLOSE(file);
6664
        return WOLFSSL_BAD_FILE;
6665
    }
6666
6667
    sz = XFTELL(file);
6668
6669
    if (XFSEEK(file, 0, XSEEK_SET) != 0) {
6670
        WOLFSSL_MSG_EX("error: crypto policy file seek failed: %s",
6671
                       policy_file);
6672
        XFCLOSE(file);
6673
        return WOLFSSL_BAD_FILE;
6674
    }
6675
6676
    if (sz <= 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
6677
        WOLFSSL_MSG_EX("error: crypto policy file %s, invalid size: %ld",
6678
                       policy_file, sz);
6679
        XFCLOSE(file);
6680
        return WOLFSSL_BAD_FILE;
6681
    }
6682
6683
    n_read = XFREAD(crypto_policy.str, 1, sz, file);
6684
    XFCLOSE(file);
6685
6686
    if (n_read != (size_t) sz) {
6687
        WOLFSSL_MSG_EX("error: crypto policy file %s: read %zu, "
6688
                       "expected %ld", policy_file, n_read, sz);
6689
        return WOLFSSL_BAD_FILE;
6690
    }
6691
6692
    crypto_policy.str[n_read] = '\0';
6693
6694
    return crypto_policy_parse();
6695
}
6696
#endif /* ! NO_FILESYSTEM */
6697
6698
/* Same behavior as wolfSSL_crypto_policy_enable, but loads
6699
 * via memory buf instead of file.
6700
 *
6701
 * Returns WOLFSSL_SUCCESS on success.
6702
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
6703
 * Returns < 0 on misc error.
6704
 * */
6705
int wolfSSL_crypto_policy_enable_buffer(const char * buf)
6706
{
6707
    size_t sz = 0;
6708
6709
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable_buffer");
6710
6711
    if (wolfSSL_crypto_policy_is_enabled()) {
6712
        WOLFSSL_MSG_EX("error: crypto policy already enabled");
6713
        return CRYPTO_POLICY_FORBIDDEN;
6714
    }
6715
6716
    if (buf == NULL || *buf == '\0') {
6717
        return BAD_FUNC_ARG;
6718
    }
6719
6720
    sz = XSTRLEN(buf);
6721
6722
    if (sz == 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
6723
        return BAD_FUNC_ARG;
6724
    }
6725
6726
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
6727
    XMEMCPY(crypto_policy.str, buf, sz);
6728
6729
    return crypto_policy_parse();
6730
}
6731
6732
/* Returns whether the system wide crypto-policy is enabled.
6733
 *
6734
 * Returns 1 if enabled.
6735
 *         0 if disabled.
6736
 * */
6737
int wolfSSL_crypto_policy_is_enabled(void)
6738
{
6739
    WOLFSSL_ENTER("wolfSSL_crypto_policy_is_enabled");
6740
6741
    return crypto_policy.enabled == 1;
6742
}
6743
6744
/* Disables the system wide crypto-policy.
6745
 * note: SSL and CTX structures already instantiated will
6746
 * keep their security policy parameters. This will only
6747
 * affect new instantiations.
6748
 * */
6749
void wolfSSL_crypto_policy_disable(void)
6750
{
6751
    WOLFSSL_ENTER("wolfSSL_crypto_policy_disable");
6752
    crypto_policy.enabled = 0;
6753
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
6754
    return;
6755
}
6756
6757
/* Get the crypto-policy bulk cipher list string.
6758
 * String is not owned by caller, should not be freed.
6759
 *
6760
 * Returns pointer to bulk cipher list string.
6761
 * Returns NULL if NOT enabled, or on error.
6762
 * */
6763
const char * wolfSSL_crypto_policy_get_ciphers(void)
6764
{
6765
    WOLFSSL_ENTER("wolfSSL_crypto_policy_get_ciphers");
6766
6767
    if (crypto_policy.enabled == 1) {
6768
        /* The crypto policy config will have
6769
         * this form:
6770
         *   "@SECLEVEL=2:kEECDH:kRSA..." */
6771
        return crypto_policy.str;
6772
    }
6773
6774
    return NULL;
6775
}
6776
6777
/* Get the configured crypto-policy security level.
6778
 * A security level of 0 does not impose any additional
6779
 * restrictions.
6780
 *
6781
 * Returns 1 - 5 if enabled.
6782
 * Returns 0 if NOT enabled.
6783
 * */
6784
int wolfSSL_crypto_policy_get_level(void)
6785
{
6786
    if (crypto_policy.enabled == 1) {
6787
        return crypto_policy.secLevel;
6788
    }
6789
6790
    return 0;
6791
}
6792
6793
/* Get security level from ssl structure.
6794
 * @param ssl  a pointer to WOLFSSL structure
6795
 */
6796
int wolfSSL_get_security_level(const WOLFSSL * ssl)
6797
{
6798
    if (ssl == NULL) {
6799
        return BAD_FUNC_ARG;
6800
    }
6801
6802
    return ssl->secLevel;
6803
}
6804
6805
#ifndef NO_WOLFSSL_STUB
6806
/*
6807
 * Set security level (wolfSSL doesn't support setting the security level).
6808
 *
6809
 * The security level can only be set through a system wide crypto-policy
6810
 * with wolfSSL_crypto_policy_enable().
6811
 *
6812
 * @param ssl  a pointer to WOLFSSL structure
6813
 * @param level security level
6814
 */
6815
void wolfSSL_set_security_level(WOLFSSL * ssl, int level)
6816
{
6817
    WOLFSSL_ENTER("wolfSSL_set_security_level");
6818
    (void)ssl;
6819
    (void)level;
6820
}
6821
#endif /* !NO_WOLFSSL_STUB */
6822
6823
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
6824
6825
6826
#define WOLFSSL_SSL_LOAD_INCLUDED
6827
#include <src/ssl_load.c>
6828
6829
#ifndef NO_CERTS
6830
6831
#ifdef HAVE_CRL
6832
6833
int wolfSSL_CTX_LoadCRLBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
6834
                              long sz, int type)
6835
{
6836
    WOLFSSL_ENTER("wolfSSL_CTX_LoadCRLBuffer");
6837
6838
    if (ctx == NULL)
6839
        return BAD_FUNC_ARG;
6840
6841
    return wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, buff, sz, type);
6842
}
6843
6844
6845
int wolfSSL_LoadCRLBuffer(WOLFSSL* ssl, const unsigned char* buff,
6846
                          long sz, int type)
6847
{
6848
    WOLFSSL_ENTER("wolfSSL_LoadCRLBuffer");
6849
6850
    if (ssl == NULL || ssl->ctx == NULL)
6851
        return BAD_FUNC_ARG;
6852
6853
    SSL_CM_WARNING(ssl);
6854
    return wolfSSL_CertManagerLoadCRLBuffer(SSL_CM(ssl), buff, sz, type);
6855
}
6856
6857
#endif /* HAVE_CRL */
6858
6859
#ifdef HAVE_OCSP
6860
int wolfSSL_EnableOCSP(WOLFSSL* ssl, int options)
6861
{
6862
    WOLFSSL_ENTER("wolfSSL_EnableOCSP");
6863
    if (ssl) {
6864
        SSL_CM_WARNING(ssl);
6865
        return wolfSSL_CertManagerEnableOCSP(SSL_CM(ssl), options);
6866
    }
6867
    else
6868
        return BAD_FUNC_ARG;
6869
}
6870
6871
int wolfSSL_DisableOCSP(WOLFSSL* ssl)
6872
{
6873
    WOLFSSL_ENTER("wolfSSL_DisableOCSP");
6874
    if (ssl) {
6875
        SSL_CM_WARNING(ssl);
6876
        return wolfSSL_CertManagerDisableOCSP(SSL_CM(ssl));
6877
    }
6878
    else
6879
        return BAD_FUNC_ARG;
6880
}
6881
6882
6883
int wolfSSL_EnableOCSPStapling(WOLFSSL* ssl)
6884
{
6885
    WOLFSSL_ENTER("wolfSSL_EnableOCSPStapling");
6886
    if (ssl) {
6887
        SSL_CM_WARNING(ssl);
6888
        return wolfSSL_CertManagerEnableOCSPStapling(SSL_CM(ssl));
6889
    }
6890
    else
6891
        return BAD_FUNC_ARG;
6892
}
6893
6894
int wolfSSL_DisableOCSPStapling(WOLFSSL* ssl)
6895
{
6896
    WOLFSSL_ENTER("wolfSSL_DisableOCSPStapling");
6897
    if (ssl) {
6898
        SSL_CM_WARNING(ssl);
6899
        return wolfSSL_CertManagerDisableOCSPStapling(SSL_CM(ssl));
6900
    }
6901
    else
6902
        return BAD_FUNC_ARG;
6903
}
6904
6905
int wolfSSL_SetOCSP_OverrideURL(WOLFSSL* ssl, const char* url)
6906
{
6907
    WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL");
6908
    if (ssl) {
6909
        SSL_CM_WARNING(ssl);
6910
        return wolfSSL_CertManagerSetOCSPOverrideURL(SSL_CM(ssl), url);
6911
    }
6912
    else
6913
        return BAD_FUNC_ARG;
6914
}
6915
6916
6917
int wolfSSL_SetOCSP_Cb(WOLFSSL* ssl,
6918
                        CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx)
6919
{
6920
    WOLFSSL_ENTER("wolfSSL_SetOCSP_Cb");
6921
    if (ssl) {
6922
        SSL_CM_WARNING(ssl);
6923
        ssl->ocspIOCtx = ioCbCtx; /* use SSL specific ioCbCtx */
6924
        return wolfSSL_CertManagerSetOCSP_Cb(SSL_CM(ssl),
6925
                                             ioCb, respFreeCb, NULL);
6926
    }
6927
    else
6928
        return BAD_FUNC_ARG;
6929
}
6930
6931
int wolfSSL_CTX_EnableOCSP(WOLFSSL_CTX* ctx, int options)
6932
{
6933
    WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSP");
6934
    if (ctx)
6935
        return wolfSSL_CertManagerEnableOCSP(ctx->cm, options);
6936
    else
6937
        return BAD_FUNC_ARG;
6938
}
6939
6940
6941
int wolfSSL_CTX_DisableOCSP(WOLFSSL_CTX* ctx)
6942
{
6943
    WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSP");
6944
    if (ctx)
6945
        return wolfSSL_CertManagerDisableOCSP(ctx->cm);
6946
    else
6947
        return BAD_FUNC_ARG;
6948
}
6949
6950
6951
int wolfSSL_CTX_SetOCSP_OverrideURL(WOLFSSL_CTX* ctx, const char* url)
6952
{
6953
    WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL");
6954
    if (ctx)
6955
        return wolfSSL_CertManagerSetOCSPOverrideURL(ctx->cm, url);
6956
    else
6957
        return BAD_FUNC_ARG;
6958
}
6959
6960
6961
int wolfSSL_CTX_SetOCSP_Cb(WOLFSSL_CTX* ctx, CbOCSPIO ioCb,
6962
                           CbOCSPRespFree respFreeCb, void* ioCbCtx)
6963
{
6964
    WOLFSSL_ENTER("wolfSSL_CTX_SetOCSP_Cb");
6965
    if (ctx)
6966
        return wolfSSL_CertManagerSetOCSP_Cb(ctx->cm, ioCb,
6967
                                             respFreeCb, ioCbCtx);
6968
    else
6969
        return BAD_FUNC_ARG;
6970
}
6971
6972
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
6973
 || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
6974
int wolfSSL_CTX_EnableOCSPStapling(WOLFSSL_CTX* ctx)
6975
{
6976
    WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPStapling");
6977
    if (ctx)
6978
        return wolfSSL_CertManagerEnableOCSPStapling(ctx->cm);
6979
    else
6980
        return BAD_FUNC_ARG;
6981
}
6982
6983
int wolfSSL_CTX_DisableOCSPStapling(WOLFSSL_CTX* ctx)
6984
{
6985
    WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPStapling");
6986
    if (ctx)
6987
        return wolfSSL_CertManagerDisableOCSPStapling(ctx->cm);
6988
    else
6989
        return BAD_FUNC_ARG;
6990
}
6991
6992
int wolfSSL_CTX_EnableOCSPMustStaple(WOLFSSL_CTX* ctx)
6993
{
6994
    WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPMustStaple");
6995
    if (ctx)
6996
        return wolfSSL_CertManagerEnableOCSPMustStaple(ctx->cm);
6997
    else
6998
        return BAD_FUNC_ARG;
6999
}
7000
7001
int wolfSSL_CTX_DisableOCSPMustStaple(WOLFSSL_CTX* ctx)
7002
{
7003
    WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPMustStaple");
7004
    if (ctx)
7005
        return wolfSSL_CertManagerDisableOCSPMustStaple(ctx->cm);
7006
    else
7007
        return BAD_FUNC_ARG;
7008
}
7009
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST || \
7010
        * HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
7011
7012
#endif /* HAVE_OCSP */
7013
7014
#ifdef HAVE_CRL
7015
7016
int wolfSSL_EnableCRL(WOLFSSL* ssl, int options)
7017
{
7018
    WOLFSSL_ENTER("wolfSSL_EnableCRL");
7019
    if (ssl) {
7020
        SSL_CM_WARNING(ssl);
7021
        return wolfSSL_CertManagerEnableCRL(SSL_CM(ssl), options);
7022
    }
7023
    else
7024
        return BAD_FUNC_ARG;
7025
}
7026
7027
7028
int wolfSSL_DisableCRL(WOLFSSL* ssl)
7029
{
7030
    WOLFSSL_ENTER("wolfSSL_DisableCRL");
7031
    if (ssl) {
7032
        SSL_CM_WARNING(ssl);
7033
        return wolfSSL_CertManagerDisableCRL(SSL_CM(ssl));
7034
    }
7035
    else
7036
        return BAD_FUNC_ARG;
7037
}
7038
7039
#ifndef NO_FILESYSTEM
7040
int wolfSSL_LoadCRL(WOLFSSL* ssl, const char* path, int type, int monitor)
7041
{
7042
    WOLFSSL_ENTER("wolfSSL_LoadCRL");
7043
    if (ssl) {
7044
        SSL_CM_WARNING(ssl);
7045
        return wolfSSL_CertManagerLoadCRL(SSL_CM(ssl), path, type, monitor);
7046
    }
7047
    else
7048
        return BAD_FUNC_ARG;
7049
}
7050
7051
int wolfSSL_LoadCRLFile(WOLFSSL* ssl, const char* file, int type)
7052
{
7053
    WOLFSSL_ENTER("wolfSSL_LoadCRLFile");
7054
    if (ssl) {
7055
        SSL_CM_WARNING(ssl);
7056
        return wolfSSL_CertManagerLoadCRLFile(SSL_CM(ssl), file, type);
7057
    }
7058
    else
7059
        return BAD_FUNC_ARG;
7060
}
7061
#endif
7062
7063
int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb)
7064
{
7065
    WOLFSSL_ENTER("wolfSSL_SetCRL_Cb");
7066
    if (ssl) {
7067
        SSL_CM_WARNING(ssl);
7068
        return wolfSSL_CertManagerSetCRL_Cb(SSL_CM(ssl), cb);
7069
    }
7070
    else
7071
        return BAD_FUNC_ARG;
7072
}
7073
7074
int wolfSSL_SetCRL_ErrorCb(WOLFSSL* ssl, crlErrorCb cb, void* ctx)
7075
{
7076
    WOLFSSL_ENTER("wolfSSL_SetCRL_Cb");
7077
    if (ssl) {
7078
        SSL_CM_WARNING(ssl);
7079
        return wolfSSL_CertManagerSetCRL_ErrorCb(SSL_CM(ssl), cb, ctx);
7080
    }
7081
    else
7082
        return BAD_FUNC_ARG;
7083
}
7084
7085
#ifdef HAVE_CRL_IO
7086
int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb)
7087
{
7088
    WOLFSSL_ENTER("wolfSSL_SetCRL_Cb");
7089
    if (ssl) {
7090
        SSL_CM_WARNING(ssl);
7091
        return wolfSSL_CertManagerSetCRL_IOCb(SSL_CM(ssl), cb);
7092
    }
7093
    else
7094
        return BAD_FUNC_ARG;
7095
}
7096
#endif
7097
7098
int wolfSSL_CTX_EnableCRL(WOLFSSL_CTX* ctx, int options)
7099
{
7100
    WOLFSSL_ENTER("wolfSSL_CTX_EnableCRL");
7101
    if (ctx)
7102
        return wolfSSL_CertManagerEnableCRL(ctx->cm, options);
7103
    else
7104
        return BAD_FUNC_ARG;
7105
}
7106
7107
7108
int wolfSSL_CTX_DisableCRL(WOLFSSL_CTX* ctx)
7109
{
7110
    WOLFSSL_ENTER("wolfSSL_CTX_DisableCRL");
7111
    if (ctx)
7112
        return wolfSSL_CertManagerDisableCRL(ctx->cm);
7113
    else
7114
        return BAD_FUNC_ARG;
7115
}
7116
7117
7118
#ifndef NO_FILESYSTEM
7119
int wolfSSL_CTX_LoadCRL(WOLFSSL_CTX* ctx, const char* path,
7120
                        int type, int monitor)
7121
{
7122
    WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL");
7123
    if (ctx)
7124
        return wolfSSL_CertManagerLoadCRL(ctx->cm, path, type, monitor);
7125
    else
7126
        return BAD_FUNC_ARG;
7127
}
7128
7129
int wolfSSL_CTX_LoadCRLFile(WOLFSSL_CTX* ctx, const char* file,
7130
                        int type)
7131
{
7132
    WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL");
7133
    if (ctx)
7134
        return wolfSSL_CertManagerLoadCRLFile(ctx->cm, file, type);
7135
    else
7136
        return BAD_FUNC_ARG;
7137
}
7138
#endif
7139
7140
7141
int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb)
7142
{
7143
    WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_Cb");
7144
    if (ctx)
7145
        return wolfSSL_CertManagerSetCRL_Cb(ctx->cm, cb);
7146
    else
7147
        return BAD_FUNC_ARG;
7148
}
7149
7150
int wolfSSL_CTX_SetCRL_ErrorCb(WOLFSSL_CTX* ctx, crlErrorCb cb, void* cbCtx)
7151
{
7152
    WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_ErrorCb");
7153
    if (ctx)
7154
        return wolfSSL_CertManagerSetCRL_ErrorCb(ctx->cm, cb, cbCtx);
7155
    else
7156
        return BAD_FUNC_ARG;
7157
}
7158
7159
#ifdef HAVE_CRL_IO
7160
int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb)
7161
{
7162
    WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_IOCb");
7163
    if (ctx)
7164
        return wolfSSL_CertManagerSetCRL_IOCb(ctx->cm, cb);
7165
    else
7166
        return BAD_FUNC_ARG;
7167
}
7168
#endif
7169
7170
7171
#endif /* HAVE_CRL */
7172
7173
7174
/* Sets the max chain depth when verifying a certificate chain. Default depth
7175
 * is set to MAX_CHAIN_DEPTH.
7176
 *
7177
 * ctx   WOLFSSL_CTX structure to set depth in
7178
 * depth max depth
7179
 */
7180
0
void wolfSSL_CTX_set_verify_depth(WOLFSSL_CTX *ctx, int depth) {
7181
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_verify_depth");
7182
7183
0
    if (ctx == NULL || depth < 0 || depth > MAX_CHAIN_DEPTH) {
7184
0
        WOLFSSL_MSG("Bad depth argument, too large or less than 0");
7185
0
        return;
7186
0
    }
7187
7188
0
    ctx->verifyDepth = (byte)depth;
7189
0
}
7190
7191
7192
/* get cert chaining depth using ssl struct */
7193
long wolfSSL_get_verify_depth(WOLFSSL* ssl)
7194
0
{
7195
0
    if(ssl == NULL) {
7196
0
        return BAD_FUNC_ARG;
7197
0
    }
7198
0
#ifndef OPENSSL_EXTRA
7199
0
    return MAX_CHAIN_DEPTH;
7200
#else
7201
    return ssl->options.verifyDepth;
7202
#endif
7203
0
}
7204
7205
7206
/* get cert chaining depth using ctx struct */
7207
long wolfSSL_CTX_get_verify_depth(WOLFSSL_CTX* ctx)
7208
0
{
7209
0
    if (ctx == NULL) {
7210
0
        return BAD_FUNC_ARG;
7211
0
    }
7212
0
#ifndef OPENSSL_EXTRA
7213
0
    return MAX_CHAIN_DEPTH;
7214
#else
7215
    return ctx->verifyDepth;
7216
#endif
7217
0
}
7218
7219
#ifndef NO_CHECK_PRIVATE_KEY
7220
7221
#ifdef WOLF_PRIVATE_KEY_ID
7222
/* Check private against public in certificate for match using external
7223
 * device with given devId */
7224
static int check_cert_key_dev(word32 keyOID, byte* privKey, word32 privSz,
7225
    const byte* pubKey, word32 pubSz, int label, int id, void* heap, int devId)
7226
0
{
7227
0
    int ret = 0;
7228
0
    int type = 0;
7229
0
    void *pkey = NULL;
7230
7231
0
    if (privKey == NULL) {
7232
0
        return MISSING_KEY;
7233
0
    }
7234
7235
0
#ifndef NO_RSA
7236
0
    if (keyOID == RSAk) {
7237
0
        type = DYNAMIC_TYPE_RSA;
7238
0
    }
7239
0
#ifdef WC_RSA_PSS
7240
0
    if (keyOID == RSAPSSk) {
7241
0
        type = DYNAMIC_TYPE_RSA;
7242
0
    }
7243
0
#endif
7244
0
#endif
7245
0
#ifdef HAVE_ECC
7246
0
    if (keyOID == ECDSAk) {
7247
0
        type = DYNAMIC_TYPE_ECC;
7248
0
    }
7249
0
#endif
7250
#if defined(HAVE_DILITHIUM)
7251
    if ((keyOID == ML_DSA_LEVEL2k) ||
7252
        (keyOID == ML_DSA_LEVEL3k) ||
7253
        (keyOID == ML_DSA_LEVEL5k)
7254
        #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
7255
     || (keyOID == DILITHIUM_LEVEL2k)
7256
     || (keyOID == DILITHIUM_LEVEL3k)
7257
     || (keyOID == DILITHIUM_LEVEL5k)
7258
        #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
7259
        ) {
7260
        type = DYNAMIC_TYPE_DILITHIUM;
7261
    }
7262
#endif
7263
#if defined(HAVE_FALCON)
7264
    if ((keyOID == FALCON_LEVEL1k) ||
7265
        (keyOID == FALCON_LEVEL5k)) {
7266
        type = DYNAMIC_TYPE_FALCON;
7267
    }
7268
#endif
7269
7270
0
    ret = CreateDevPrivateKey(&pkey, privKey, privSz, type, label, id,
7271
0
                              heap, devId);
7272
0
    #ifdef WOLF_CRYPTO_CB
7273
0
    if (ret == 0) {
7274
0
        #ifndef NO_RSA
7275
0
        if (keyOID == RSAk
7276
0
        #ifdef WC_RSA_PSS
7277
0
            || keyOID == RSAPSSk
7278
0
        #endif
7279
0
            ) {
7280
0
            ret = wc_CryptoCb_RsaCheckPrivKey((RsaKey*)pkey, pubKey, pubSz);
7281
0
        }
7282
0
        #endif
7283
0
        #ifdef HAVE_ECC
7284
0
        if (keyOID == ECDSAk) {
7285
0
            ret = wc_CryptoCb_EccCheckPrivKey((ecc_key*)pkey, pubKey, pubSz);
7286
0
        }
7287
0
        #endif
7288
        #if defined(HAVE_DILITHIUM)
7289
        if ((keyOID == ML_DSA_LEVEL2k) ||
7290
            (keyOID == ML_DSA_LEVEL3k) ||
7291
            (keyOID == ML_DSA_LEVEL5k)
7292
            #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
7293
         || (keyOID == DILITHIUM_LEVEL2k)
7294
         || (keyOID == DILITHIUM_LEVEL3k)
7295
         || (keyOID == DILITHIUM_LEVEL5k)
7296
            #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
7297
            ) {
7298
            ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey,
7299
                                        WC_PQC_SIG_TYPE_DILITHIUM,
7300
                                        pubKey, pubSz);
7301
        }
7302
        #endif
7303
        #if defined(HAVE_FALCON)
7304
        if ((keyOID == FALCON_LEVEL1k) ||
7305
            (keyOID == FALCON_LEVEL5k)) {
7306
            ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey,
7307
                                        WC_PQC_SIG_TYPE_FALCON,
7308
                                        pubKey, pubSz);
7309
        }
7310
        #endif
7311
0
    }
7312
    #else
7313
        /* devId was set, don't check, for now */
7314
        /* TODO: Add callback for private key check? */
7315
        (void) pubKey;
7316
        (void) pubSz;
7317
    #endif
7318
0
    if (pkey != NULL) {
7319
0
    #ifndef NO_RSA
7320
0
        if (keyOID == RSAk
7321
0
        #ifdef WC_RSA_PSS
7322
0
            || keyOID == RSAPSSk
7323
0
        #endif
7324
0
            ) {
7325
0
            wc_FreeRsaKey((RsaKey*)pkey);
7326
0
        }
7327
0
    #endif
7328
0
    #ifdef HAVE_ECC
7329
0
        if (keyOID == ECDSAk) {
7330
0
            wc_ecc_free((ecc_key*)pkey);
7331
0
        }
7332
0
    #endif
7333
    #if defined(HAVE_DILITHIUM)
7334
        if ((keyOID == ML_DSA_LEVEL2k) ||
7335
            (keyOID == ML_DSA_LEVEL3k) ||
7336
            (keyOID == ML_DSA_LEVEL5k)
7337
            #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
7338
         || (keyOID == DILITHIUM_LEVEL2k)
7339
         || (keyOID == DILITHIUM_LEVEL3k)
7340
         || (keyOID == DILITHIUM_LEVEL5k)
7341
            #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
7342
            ) {
7343
            wc_dilithium_free((dilithium_key*)pkey);
7344
        }
7345
    #endif
7346
    #if defined(HAVE_FALCON)
7347
        if ((keyOID == FALCON_LEVEL1k) ||
7348
            (keyOID == FALCON_LEVEL5k)) {
7349
            wc_falcon_free((falcon_key*)pkey);
7350
        }
7351
    #endif
7352
0
        XFREE(pkey, heap, type);
7353
0
    }
7354
7355
0
    return ret;
7356
0
}
7357
#endif /* WOLF_PRIVATE_KEY_ID */
7358
7359
/* Check private against public in certificate for match
7360
 *
7361
 * Returns WOLFSSL_SUCCESS on good private key
7362
 *         WOLFSSL_FAILURE if mismatched */
7363
static int check_cert_key(const DerBuffer* cert, const DerBuffer* key,
7364
    const DerBuffer* altKey, void* heap, int devId, int isKeyLabel, int isKeyId,
7365
    int altDevId, int isAltKeyLabel, int isAltKeyId)
7366
0
{
7367
0
    WC_DECLARE_VAR(der, DecodedCert, 1, 0);
7368
0
    word32 size;
7369
0
    byte*  buff;
7370
0
    int    ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
7371
7372
0
    WOLFSSL_ENTER("check_cert_key");
7373
7374
0
    if (cert == NULL || key == NULL) {
7375
0
        return WOLFSSL_FAILURE;
7376
0
    }
7377
7378
0
    WC_ALLOC_VAR_EX(der, DecodedCert, 1, heap, DYNAMIC_TYPE_DCERT,
7379
0
        return MEMORY_E);
7380
7381
0
    size = cert->length;
7382
0
    buff = cert->buffer;
7383
0
    InitDecodedCert_ex(der, buff, size, heap, devId);
7384
0
    if (ParseCertRelative(der, CERT_TYPE, NO_VERIFY, NULL, NULL) != 0) {
7385
0
        FreeDecodedCert(der);
7386
0
        WC_FREE_VAR_EX(der, heap, DYNAMIC_TYPE_DCERT);
7387
0
        return WOLFSSL_FAILURE;
7388
0
    }
7389
7390
0
    size = key->length;
7391
0
    buff = key->buffer;
7392
0
#ifdef WOLF_PRIVATE_KEY_ID
7393
0
    if (devId != INVALID_DEVID) {
7394
0
        ret = check_cert_key_dev(der->keyOID, buff, size, der->publicKey,
7395
0
                                 der->pubKeySize, isKeyLabel, isKeyId, heap,
7396
0
                                 devId);
7397
0
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
7398
0
            ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
7399
0
        }
7400
0
    }
7401
0
    else {
7402
        /* fall through if unavailable */
7403
0
        ret = CRYPTOCB_UNAVAILABLE;
7404
0
    }
7405
7406
0
    if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
7407
0
#endif /* WOLF_PRIVATE_KEY_ID */
7408
0
    {
7409
0
        ret = wc_CheckPrivateKeyCert(buff, size, der, 0, heap);
7410
0
        ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
7411
0
    }
7412
7413
#ifdef WOLFSSL_DUAL_ALG_CERTS
7414
    if (ret == WOLFSSL_SUCCESS && der->extSapkiSet && der->sapkiDer != NULL) {
7415
        /* Certificate contains an alternative public key. Hence, we also
7416
         * need an alternative private key. */
7417
        if (altKey == NULL) {
7418
            ret = MISSING_KEY;
7419
            buff = NULL;
7420
            size = 0;
7421
        }
7422
        else {
7423
            size = altKey->length;
7424
            buff = altKey->buffer;
7425
        }
7426
#ifdef WOLF_PRIVATE_KEY_ID
7427
        if (ret == WOLFSSL_SUCCESS && altDevId != INVALID_DEVID) {
7428
            /* We have to decode the public key first */
7429
            /* Default to max pub key size. */
7430
            word32 pubKeyLen = MAX_PUBLIC_KEY_SZ;
7431
            byte* decodedPubKey = (byte*)XMALLOC(pubKeyLen, heap,
7432
                                            DYNAMIC_TYPE_PUBLIC_KEY);
7433
            if (decodedPubKey == NULL) {
7434
                ret = MEMORY_E;
7435
            }
7436
            if (ret == WOLFSSL_SUCCESS) {
7437
                if (der->sapkiOID == RSAk || der->sapkiOID == ECDSAk) {
7438
                    /* Simply copy the data */
7439
                    XMEMCPY(decodedPubKey, der->sapkiDer, der->sapkiLen);
7440
                    pubKeyLen = der->sapkiLen;
7441
                    ret = 0;
7442
                }
7443
                else {
7444
                #if defined(WC_ENABLE_ASYM_KEY_IMPORT)
7445
                    word32 idx = 0;
7446
                    ret = DecodeAsymKeyPublic(der->sapkiDer, &idx,
7447
                                              der->sapkiLen, decodedPubKey,
7448
                                              &pubKeyLen, der->sapkiOID);
7449
                #else
7450
                    ret = NOT_COMPILED_IN;
7451
                #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
7452
                }
7453
            }
7454
            if (ret == 0) {
7455
                ret = check_cert_key_dev(der->sapkiOID, buff, size,
7456
                                         decodedPubKey, pubKeyLen,
7457
                                         isAltKeyLabel, isAltKeyId,
7458
                                         heap, altDevId);
7459
            }
7460
            XFREE(decodedPubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
7461
            if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
7462
                ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
7463
            }
7464
        }
7465
        else {
7466
            /* fall through if unavailable */
7467
            ret = CRYPTOCB_UNAVAILABLE;
7468
        }
7469
7470
        if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
7471
#else
7472
        if (ret == WOLFSSL_SUCCESS)
7473
#endif /* WOLF_PRIVATE_KEY_ID */
7474
        {
7475
            ret = wc_CheckPrivateKeyCert(buff, size, der, 1, heap);
7476
            ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
7477
        }
7478
    }
7479
#endif /* WOLFSSL_DUAL_ALG_CERTS */
7480
0
    FreeDecodedCert(der);
7481
0
    WC_FREE_VAR_EX(der, heap, DYNAMIC_TYPE_DCERT);
7482
7483
0
    (void)devId;
7484
0
    (void)isKeyLabel;
7485
0
    (void)isKeyId;
7486
0
    (void)altKey;
7487
0
    (void)altDevId;
7488
0
    (void)isAltKeyLabel;
7489
0
    (void)isAltKeyId;
7490
7491
0
    return ret;
7492
0
}
7493
7494
/* Check private against public in certificate for match
7495
 *
7496
 * ctx  WOLFSSL_CTX structure to check private key in
7497
 *
7498
 * Returns WOLFSSL_SUCCESS on good private key
7499
 *         WOLFSSL_FAILURE if mismatched. */
7500
int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx)
7501
0
{
7502
0
    int res = WOLFSSL_SUCCESS;
7503
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
7504
    DerBuffer *privateKey;
7505
#ifdef WOLFSSL_DUAL_ALG_CERTS
7506
    DerBuffer *altPrivateKey;
7507
#endif
7508
#else
7509
0
    const DerBuffer *privateKey;
7510
#ifdef WOLFSSL_DUAL_ALG_CERTS
7511
    const DerBuffer *altPrivateKey;
7512
#endif
7513
0
#endif
7514
7515
0
    if (ctx == NULL) {
7516
0
        return WOLFSSL_FAILURE;
7517
0
    }
7518
7519
#ifdef WOLFSSL_DUAL_ALG_CERTS
7520
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
7521
    privateKey = wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask);
7522
    altPrivateKey = wolfssl_priv_der_unblind(ctx->altPrivateKey,
7523
                                             ctx->altPrivateKeyMask);
7524
    if ((privateKey == NULL) || (altPrivateKey == NULL)) {
7525
        res = WOLFSSL_FAILURE;
7526
    }
7527
#else
7528
    privateKey = ctx->privateKey;
7529
    altPrivateKey = ctx->altPrivateKey;
7530
#endif
7531
    if (res == WOLFSSL_SUCCESS) {
7532
        res = check_cert_key(ctx->certificate, privateKey, altPrivateKey,
7533
                             ctx->heap, ctx->privateKeyDevId, ctx->privateKeyLabel,
7534
                             ctx->privateKeyId, ctx->altPrivateKeyDevId,
7535
                             ctx->altPrivateKeyLabel, ctx->altPrivateKeyId) != 0;
7536
    }
7537
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
7538
    wolfssl_priv_der_unblind_free(privateKey);
7539
    wolfssl_priv_der_unblind_free(altPrivateKey);
7540
#endif
7541
#else
7542
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
7543
    privateKey = wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask);
7544
    if (privateKey == NULL) {
7545
        res = WOLFSSL_FAILURE;
7546
    }
7547
#else
7548
0
    privateKey = ctx->privateKey;
7549
0
#endif
7550
0
    if (res == WOLFSSL_SUCCESS) {
7551
0
        res = check_cert_key(ctx->certificate, privateKey, NULL, ctx->heap,
7552
0
                             ctx->privateKeyDevId, ctx->privateKeyLabel,
7553
0
                             ctx->privateKeyId, INVALID_DEVID, 0, 0);
7554
0
    }
7555
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
7556
    wolfssl_priv_der_unblind_free(privateKey);
7557
#endif
7558
0
#endif
7559
7560
    /* placing error into error queue for Python port */
7561
0
    if (res != WOLFSSL_SUCCESS) {
7562
0
        WOLFSSL_ERROR(WC_KEY_MISMATCH_E);
7563
0
    }
7564
7565
0
    return res;
7566
0
}
7567
#endif /* !NO_CHECK_PRIVATE_KEY */
7568
7569
#ifdef OPENSSL_ALL
7570
/**
7571
 * Return the private key of the WOLFSSL_CTX struct
7572
 * @return WOLFSSL_EVP_PKEY* The caller doesn *NOT*` free the returned object.
7573
 *
7574
 * Note, even though the supplied ctx pointer is designated const, on success
7575
 * ctx->privateKeyPKey is changed by this call.  The change is done safely using
7576
 * a hardware-synchronized store.
7577
 */
7578
WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx)
7579
{
7580
    WOLFSSL_EVP_PKEY* res;
7581
    const unsigned char *key;
7582
    int type;
7583
7584
    WOLFSSL_ENTER("wolfSSL_CTX_get0_privatekey");
7585
7586
    if (ctx == NULL || ctx->privateKey == NULL ||
7587
            ctx->privateKey->buffer == NULL) {
7588
        WOLFSSL_MSG("Bad parameter or key not set");
7589
        return NULL;
7590
    }
7591
7592
    switch (ctx->privateKeyType) {
7593
#ifndef NO_RSA
7594
        case rsa_sa_algo:
7595
            type = WC_EVP_PKEY_RSA;
7596
            break;
7597
#endif
7598
#ifdef HAVE_ECC
7599
        case ecc_dsa_sa_algo:
7600
            type = WC_EVP_PKEY_EC;
7601
            break;
7602
#endif
7603
#ifdef WOLFSSL_SM2
7604
        case sm2_sa_algo:
7605
            type = WC_EVP_PKEY_EC;
7606
            break;
7607
#endif
7608
        default:
7609
            /* Other key types not supported either as ssl private keys
7610
             * or in the EVP layer */
7611
            WOLFSSL_MSG("Unsupported key type");
7612
            return NULL;
7613
    }
7614
7615
    if (ctx->privateKeyPKey != NULL) {
7616
        res = ctx->privateKeyPKey;
7617
    }
7618
    else {
7619
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
7620
        DerBuffer *unblinded_privateKey =
7621
            wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask);
7622
        if (unblinded_privateKey == NULL)
7623
            return NULL;
7624
        key = unblinded_privateKey->buffer;
7625
    #else
7626
        key = ctx->privateKey->buffer;
7627
    #endif
7628
        res = wolfSSL_d2i_PrivateKey(type, NULL, &key,
7629
                (long)ctx->privateKey->length);
7630
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
7631
        wolfssl_priv_der_unblind_free(unblinded_privateKey);
7632
    #endif
7633
        if (res) {
7634
#ifdef WOLFSSL_ATOMIC_OPS
7635
            WOLFSSL_EVP_PKEY *current_pkey = NULL;
7636
            if (! wolfSSL_Atomic_Ptr_CompareExchange(
7637
                    (void * volatile *)&ctx->privateKeyPKey,
7638
                    (void **)&current_pkey, res))
7639
            {
7640
                wolfSSL_EVP_PKEY_free(res);
7641
                res = current_pkey;
7642
            }
7643
#else
7644
            ((WOLFSSL_CTX *)ctx)->privateKeyPKey = res;
7645
#endif
7646
        }
7647
    }
7648
7649
    return res;
7650
}
7651
#endif
7652
7653
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
7654
7655
#if !defined(NO_RSA)
7656
static int d2iTryRsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
7657
    long memSz, int priv)
7658
{
7659
    WOLFSSL_EVP_PKEY* pkey;
7660
    word32 keyIdx = 0;
7661
    int isRsaKey;
7662
    int ret = 1;
7663
#ifndef WOLFSSL_SMALL_STACK
7664
    RsaKey rsa[1];
7665
#else
7666
    RsaKey *rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
7667
    if (rsa == NULL)
7668
        return 0;
7669
#endif
7670
7671
    XMEMSET(rsa, 0, sizeof(RsaKey));
7672
7673
    if (wc_InitRsaKey(rsa, NULL) != 0) {
7674
        WC_FREE_VAR_EX(rsa, NULL, DYNAMIC_TYPE_RSA);
7675
        return 0;
7676
    }
7677
    /* test if RSA key */
7678
    if (priv) {
7679
        isRsaKey =
7680
            (wc_RsaPrivateKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0);
7681
    }
7682
    else {
7683
        isRsaKey =
7684
            (wc_RsaPublicKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0);
7685
    }
7686
    wc_FreeRsaKey(rsa);
7687
    WC_FREE_VAR_EX(rsa, NULL, DYNAMIC_TYPE_RSA);
7688
7689
    if (!isRsaKey) {
7690
        return WOLFSSL_FATAL_ERROR;
7691
    }
7692
7693
    if (*out != NULL) {
7694
        pkey = *out;
7695
    }
7696
    else {
7697
        pkey = wolfSSL_EVP_PKEY_new();
7698
        if (pkey == NULL) {
7699
            WOLFSSL_MSG("RSA wolfSSL_EVP_PKEY_new error");
7700
            return 0;
7701
        }
7702
    }
7703
7704
    pkey->pkey_sz = (int)keyIdx;
7705
    pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL,
7706
            priv ? DYNAMIC_TYPE_PRIVATE_KEY :
7707
                   DYNAMIC_TYPE_PUBLIC_KEY);
7708
    if (pkey->pkey.ptr == NULL) {
7709
        ret = 0;
7710
    }
7711
    if (ret == 1) {
7712
        XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
7713
        pkey->type = WC_EVP_PKEY_RSA;
7714
7715
        pkey->ownRsa = 1;
7716
        pkey->rsa = wolfssl_rsa_d2i(NULL, mem, memSz,
7717
            priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC);
7718
        if (pkey->rsa == NULL) {
7719
            ret = 0;
7720
        }
7721
    }
7722
7723
    if (ret == 1) {
7724
        *out = pkey;
7725
    }
7726
7727
    if ((ret == 0) && (*out == NULL)) {
7728
        wolfSSL_EVP_PKEY_free(pkey);
7729
    }
7730
    return ret;
7731
}
7732
#endif /* !NO_RSA */
7733
7734
#if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
7735
static int d2iTryEccKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
7736
    long memSz, int priv)
7737
{
7738
    WOLFSSL_EVP_PKEY* pkey;
7739
    word32  keyIdx = 0;
7740
    int     isEccKey;
7741
    int     ret = 1;
7742
#ifndef WOLFSSL_SMALL_STACK
7743
    ecc_key ecc[1];
7744
#else
7745
    ecc_key *ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL,
7746
        DYNAMIC_TYPE_ECC);
7747
    if (ecc == NULL)
7748
        return 0;
7749
#endif
7750
7751
    XMEMSET(ecc, 0, sizeof(ecc_key));
7752
7753
    if (wc_ecc_init(ecc) != 0) {
7754
        WC_FREE_VAR_EX(ecc, NULL, DYNAMIC_TYPE_ECC);
7755
        return 0;
7756
    }
7757
7758
    if (priv) {
7759
        isEccKey =
7760
            (wc_EccPrivateKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0);
7761
    }
7762
    else {
7763
        isEccKey =
7764
            (wc_EccPublicKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0);
7765
    }
7766
    wc_ecc_free(ecc);
7767
    WC_FREE_VAR_EX(ecc, NULL, DYNAMIC_TYPE_ECC);
7768
7769
    if (!isEccKey) {
7770
        return WOLFSSL_FATAL_ERROR;
7771
    }
7772
7773
    if (*out != NULL) {
7774
        pkey = *out;
7775
    }
7776
    else {
7777
        pkey = wolfSSL_EVP_PKEY_new();
7778
        if (pkey == NULL) {
7779
            WOLFSSL_MSG("ECC wolfSSL_EVP_PKEY_new error");
7780
            return 0;
7781
        }
7782
    }
7783
7784
    pkey->pkey_sz = (int)keyIdx;
7785
    pkey->pkey.ptr = (char*)XMALLOC(keyIdx, NULL,
7786
            priv ? DYNAMIC_TYPE_PRIVATE_KEY :
7787
                   DYNAMIC_TYPE_PUBLIC_KEY);
7788
    if (pkey->pkey.ptr == NULL) {
7789
        ret = 0;
7790
    }
7791
    if (ret == 1) {
7792
        XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
7793
        pkey->type = WC_EVP_PKEY_EC;
7794
7795
        pkey->ownEcc = 1;
7796
        pkey->ecc = wolfSSL_EC_KEY_new();
7797
        if (pkey->ecc == NULL) {
7798
            ret = 0;
7799
        }
7800
    }
7801
    if ((ret == 1) && (wolfSSL_EC_KEY_LoadDer_ex(pkey->ecc,
7802
            (const unsigned char*)pkey->pkey.ptr,
7803
            pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE
7804
                                : WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
7805
        ret = 0;
7806
    }
7807
    if (ret == 1) {
7808
        *out = pkey;
7809
    }
7810
7811
    if ((ret == 0) && (*out == NULL)) {
7812
        wolfSSL_EVP_PKEY_free(pkey);
7813
    }
7814
    return ret;
7815
}
7816
#endif /* HAVE_ECC && OPENSSL_EXTRA */
7817
7818
#if !defined(NO_DSA)
7819
static int d2iTryDsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
7820
    long memSz, int priv)
7821
{
7822
    WOLFSSL_EVP_PKEY* pkey;
7823
    word32 keyIdx = 0;
7824
    int     isDsaKey;
7825
    int     ret = 1;
7826
#ifndef WOLFSSL_SMALL_STACK
7827
    DsaKey dsa[1];
7828
#else
7829
    DsaKey *dsa = (DsaKey*)XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
7830
    if (dsa == NULL)
7831
        return 0;
7832
#endif
7833
7834
    XMEMSET(dsa, 0, sizeof(DsaKey));
7835
7836
    if (wc_InitDsaKey(dsa) != 0) {
7837
        WC_FREE_VAR_EX(dsa, NULL, DYNAMIC_TYPE_DSA);
7838
        return 0;
7839
    }
7840
7841
    if (priv) {
7842
        isDsaKey =
7843
            (wc_DsaPrivateKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0);
7844
    }
7845
    else {
7846
        isDsaKey =
7847
            (wc_DsaPublicKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0);
7848
    }
7849
    wc_FreeDsaKey(dsa);
7850
    WC_FREE_VAR_EX(dsa, NULL, DYNAMIC_TYPE_DSA);
7851
7852
    /* test if DSA key */
7853
    if (!isDsaKey) {
7854
        return WOLFSSL_FATAL_ERROR;
7855
    }
7856
7857
    if (*out != NULL) {
7858
        pkey = *out;
7859
    }
7860
    else {
7861
        pkey = wolfSSL_EVP_PKEY_new();
7862
        if (pkey == NULL) {
7863
            WOLFSSL_MSG("DSA wolfSSL_EVP_PKEY_new error");
7864
            return 0;
7865
        }
7866
    }
7867
7868
    pkey->pkey_sz = (int)keyIdx;
7869
    pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL,
7870
            priv ? DYNAMIC_TYPE_PRIVATE_KEY :
7871
                   DYNAMIC_TYPE_PUBLIC_KEY);
7872
    if (pkey->pkey.ptr == NULL) {
7873
        ret = 0;
7874
    }
7875
    if (ret == 1) {
7876
        XMEMCPY(pkey->pkey.ptr, mem, keyIdx);
7877
        pkey->type = WC_EVP_PKEY_DSA;
7878
7879
        pkey->ownDsa = 1;
7880
        pkey->dsa = wolfSSL_DSA_new();
7881
        if (pkey->dsa == NULL) {
7882
            ret = 0;
7883
        }
7884
    }
7885
7886
    if ((ret == 1) && (wolfSSL_DSA_LoadDer_ex(pkey->dsa,
7887
            (const unsigned char*)pkey->pkey.ptr,
7888
            pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE
7889
                                : WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
7890
        ret = 0;
7891
    }
7892
    if (ret == 1) {
7893
        *out = pkey;
7894
    }
7895
7896
    if ((ret == 0) && (*out == NULL)) {
7897
        wolfSSL_EVP_PKEY_free(pkey);
7898
    }
7899
    return ret;
7900
}
7901
#endif /* NO_DSA */
7902
7903
#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
7904
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
7905
    (HAVE_FIPS_VERSION > 2))
7906
static int d2iTryDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
7907
    long memSz, int priv)
7908
{
7909
    WOLFSSL_EVP_PKEY* pkey;
7910
    int isDhKey;
7911
    word32 keyIdx = 0;
7912
    int ret = 1;
7913
#ifndef WOLFSSL_SMALL_STACK
7914
    DhKey dh[1];
7915
#else
7916
    DhKey *dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
7917
    if (dh == NULL)
7918
        return 0;
7919
#endif
7920
7921
    XMEMSET(dh, 0, sizeof(DhKey));
7922
7923
    if (wc_InitDhKey(dh) != 0) {
7924
        WC_FREE_VAR_EX(dh, NULL, DYNAMIC_TYPE_DH);
7925
        return 0;
7926
    }
7927
7928
    isDhKey = (wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz) == 0);
7929
    wc_FreeDhKey(dh);
7930
    WC_FREE_VAR_EX(dh, NULL, DYNAMIC_TYPE_DH);
7931
7932
    /* test if DH key */
7933
    if (!isDhKey) {
7934
        return WOLFSSL_FATAL_ERROR;
7935
    }
7936
7937
    if (*out != NULL) {
7938
        pkey = *out;
7939
    }
7940
    else {
7941
        pkey = wolfSSL_EVP_PKEY_new();
7942
        if (pkey == NULL) {
7943
            WOLFSSL_MSG("DH wolfSSL_EVP_PKEY_new error");
7944
            return 0;
7945
        }
7946
    }
7947
7948
    pkey->pkey_sz = (int)memSz;
7949
    pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL,
7950
            priv ? DYNAMIC_TYPE_PRIVATE_KEY :
7951
                   DYNAMIC_TYPE_PUBLIC_KEY);
7952
    if (pkey->pkey.ptr == NULL) {
7953
        ret = 0;
7954
    }
7955
    if (ret == 1) {
7956
        XMEMCPY(pkey->pkey.ptr, mem, (size_t)memSz);
7957
        pkey->type = WC_EVP_PKEY_DH;
7958
7959
        pkey->ownDh = 1;
7960
        pkey->dh = wolfSSL_DH_new();
7961
        if (pkey->dh == NULL) {
7962
            ret = 0;
7963
        }
7964
    }
7965
7966
    if ((ret == 1) && (wolfSSL_DH_LoadDer(pkey->dh,
7967
                (const unsigned char*)pkey->pkey.ptr,
7968
                pkey->pkey_sz) != WOLFSSL_SUCCESS)) {
7969
        ret = 0;
7970
    }
7971
    if (ret == 1) {
7972
        *out = pkey;
7973
    }
7974
7975
    if ((ret == 0) && (*out == NULL)) {
7976
        wolfSSL_EVP_PKEY_free(pkey);
7977
    }
7978
    return ret;
7979
}
7980
#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
7981
#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
7982
7983
#if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA)
7984
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
7985
        (HAVE_FIPS_VERSION > 2))
7986
static int d2iTryAltDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
7987
    long memSz, int priv)
7988
{
7989
    WOLFSSL_EVP_PKEY* pkey;
7990
    word32  keyIdx = 0;
7991
    DhKey*  key = NULL;
7992
    int elements;
7993
    int ret;
7994
#ifndef WOLFSSL_SMALL_STACK
7995
    DhKey  dh[1];
7996
#else
7997
    DhKey* dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
7998
    if (dh == NULL)
7999
        return 0;
8000
#endif
8001
    XMEMSET(dh, 0, sizeof(DhKey));
8002
8003
    /* test if DH-public key */
8004
    if (wc_InitDhKey(dh) != 0) {
8005
        WC_FREE_VAR_EX(dh, NULL, DYNAMIC_TYPE_DH);
8006
        return 0;
8007
    }
8008
8009
    ret = wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz);
8010
    wc_FreeDhKey(dh);
8011
    WC_FREE_VAR_EX(dh, NULL, DYNAMIC_TYPE_DH);
8012
8013
    if (ret != 0) {
8014
        return WOLFSSL_FATAL_ERROR;
8015
    }
8016
8017
    if (*out != NULL) {
8018
        pkey = *out;
8019
    }
8020
    else {
8021
        pkey = wolfSSL_EVP_PKEY_new();
8022
        if (pkey == NULL) {
8023
            return 0;
8024
        }
8025
    }
8026
8027
    ret = 1;
8028
    pkey->type     = WC_EVP_PKEY_DH;
8029
    pkey->pkey_sz  = (int)memSz;
8030
    pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL,
8031
            priv ? DYNAMIC_TYPE_PRIVATE_KEY :
8032
                   DYNAMIC_TYPE_PUBLIC_KEY);
8033
    if (pkey->pkey.ptr == NULL) {
8034
        ret = 0;
8035
    }
8036
    if (ret == 1) {
8037
        XMEMCPY(pkey->pkey.ptr, mem, (size_t)memSz);
8038
        pkey->ownDh = 1;
8039
        pkey->dh = wolfSSL_DH_new();
8040
        if (pkey->dh == NULL) {
8041
            ret = 0;
8042
        }
8043
    }
8044
8045
    if (ret == 1) {
8046
        key = (DhKey*)pkey->dh->internal;
8047
8048
        keyIdx = 0;
8049
        if (wc_DhKeyDecode(mem, &keyIdx, key, (word32)memSz) != 0) {
8050
            ret = 0;
8051
        }
8052
    }
8053
8054
    if (ret == 1) {
8055
        elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | ELEMENT_PUB;
8056
        if (priv) {
8057
            elements |= ELEMENT_PRV;
8058
        }
8059
        if (SetDhExternal_ex(pkey->dh, elements) != WOLFSSL_SUCCESS ) {
8060
            ret = 0;
8061
        }
8062
    }
8063
    if (ret == 1) {
8064
        *out = pkey;
8065
    }
8066
8067
    if ((ret == 0) && (*out == NULL)) {
8068
        wolfSSL_EVP_PKEY_free(pkey);
8069
    }
8070
    return ret;
8071
}
8072
#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
8073
#endif /* !NO_DH &&  OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */
8074
8075
#ifdef HAVE_FALCON
8076
static int d2iTryFalconKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
8077
    long memSz, int priv)
8078
{
8079
    WOLFSSL_EVP_PKEY* pkey;
8080
    int isFalcon = 0;
8081
#ifndef WOLFSSL_SMALL_STACK
8082
    falcon_key falcon[1];
8083
#else
8084
    falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(falcon_key), NULL,
8085
                                              DYNAMIC_TYPE_FALCON);
8086
    if (falcon == NULL) {
8087
        return 0;
8088
    }
8089
#endif
8090
8091
    if (wc_falcon_init(falcon) != 0) {
8092
        WC_FREE_VAR_EX(falcon, NULL, DYNAMIC_TYPE_FALCON);
8093
        return 0;
8094
    }
8095
8096
    /* test if Falcon key */
8097
    if (priv) {
8098
        /* Try level 1 */
8099
        isFalcon = ((wc_falcon_set_level(falcon, 1) == 0) &&
8100
                    (wc_falcon_import_private_only(mem, (word32)memSz,
8101
                                                   falcon) == 0));
8102
        if (!isFalcon) {
8103
            /* Try level 5 */
8104
            isFalcon = ((wc_falcon_set_level(falcon, 5) == 0) &&
8105
                        (wc_falcon_import_private_only(mem, (word32)memSz,
8106
                                                       falcon) == 0));
8107
        }
8108
    }
8109
    else {
8110
        /* Try level 1 */
8111
        isFalcon = ((wc_falcon_set_level(falcon, 1) == 0) &&
8112
                    (wc_falcon_import_public(mem, (word32)memSz, falcon) == 0));
8113
8114
        if (!isFalcon) {
8115
            /* Try level 5 */
8116
            isFalcon = ((wc_falcon_set_level(falcon, 5) == 0) &&
8117
                        (wc_falcon_import_public(mem, (word32)memSz,
8118
                                                 falcon) == 0));
8119
        }
8120
    }
8121
    wc_falcon_free(falcon);
8122
    WC_FREE_VAR_EX(falcon, NULL, DYNAMIC_TYPE_FALCON);
8123
8124
    if (!isFalcon) {
8125
        return WOLFSSL_FATAL_ERROR;
8126
    }
8127
8128
    if (*out != NULL) {
8129
        pkey = *out;
8130
    }
8131
    else {
8132
        /* Create a fake Falcon EVP_PKEY. In the future, we might integrate
8133
         * Falcon into the compatibility layer. */
8134
        pkey = wolfSSL_EVP_PKEY_new();
8135
        if (pkey == NULL) {
8136
            WOLFSSL_MSG("Falcon wolfSSL_EVP_PKEY_new error");
8137
            return 0;
8138
        }
8139
    }
8140
    pkey->type = WC_EVP_PKEY_FALCON;
8141
    pkey->pkey.ptr = NULL;
8142
    pkey->pkey_sz = 0;
8143
8144
    *out = pkey;
8145
    return 1;
8146
8147
}
8148
#endif /* HAVE_FALCON */
8149
8150
#ifdef HAVE_DILITHIUM
8151
static int d2iTryDilithiumKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem,
8152
    long memSz, int priv)
8153
{
8154
    WOLFSSL_EVP_PKEY* pkey;
8155
    int isDilithium = 0;
8156
#ifndef WOLFSSL_SMALL_STACK
8157
    dilithium_key dilithium[1];
8158
#else
8159
    dilithium_key *dilithium = (dilithium_key *)
8160
        XMALLOC(sizeof(dilithium_key), NULL, DYNAMIC_TYPE_DILITHIUM);
8161
    if (dilithium == NULL) {
8162
        return 0;
8163
    }
8164
#endif
8165
8166
    if (wc_dilithium_init(dilithium) != 0) {
8167
        WC_FREE_VAR_EX(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM);
8168
        return 0;
8169
    }
8170
8171
    /* Test if Dilithium key. Try all levels. */
8172
    if (priv) {
8173
        isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) &&
8174
                       (wc_dilithium_import_private(mem,
8175
                          (word32)memSz, dilithium) == 0));
8176
        if (!isDilithium) {
8177
            isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) &&
8178
                           (wc_dilithium_import_private(mem,
8179
                              (word32)memSz, dilithium) == 0));
8180
        }
8181
        if (!isDilithium) {
8182
            isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) &&
8183
                           (wc_dilithium_import_private(mem,
8184
                              (word32)memSz, dilithium) == 0));
8185
        }
8186
    }
8187
    else {
8188
        isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) &&
8189
                       (wc_dilithium_import_public(mem, (word32)memSz,
8190
                          dilithium) == 0));
8191
        if (!isDilithium) {
8192
            isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) &&
8193
                           (wc_dilithium_import_public(mem, (word32)memSz,
8194
                              dilithium) == 0));
8195
        }
8196
        if (!isDilithium) {
8197
            isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) &&
8198
                           (wc_dilithium_import_public(mem, (word32)memSz,
8199
                              dilithium) == 0));
8200
        }
8201
    }
8202
    wc_dilithium_free(dilithium);
8203
    WC_FREE_VAR_EX(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM);
8204
8205
    if (!isDilithium) {
8206
        return WOLFSSL_FATAL_ERROR;
8207
    }
8208
8209
    if (*out != NULL) {
8210
        pkey = *out;
8211
    }
8212
    else {
8213
        /* Create a fake Dilithium EVP_PKEY. In the future, we might
8214
         * integrate Dilithium into the compatibility layer. */
8215
        pkey = wolfSSL_EVP_PKEY_new();
8216
        if (pkey == NULL) {
8217
            WOLFSSL_MSG("Dilithium wolfSSL_EVP_PKEY_new error");
8218
            return 0;
8219
        }
8220
    }
8221
    pkey->type = WC_EVP_PKEY_DILITHIUM;
8222
    pkey->pkey.ptr = NULL;
8223
    pkey->pkey_sz = 0;
8224
8225
    *out = pkey;
8226
    return 1;
8227
}
8228
#endif /* HAVE_DILITHIUM */
8229
8230
static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out,
8231
    const unsigned char** in, long inSz, int priv)
8232
{
8233
    WOLFSSL_EVP_PKEY* pkey = NULL;
8234
8235
    WOLFSSL_ENTER("d2iGenericKey");
8236
8237
    if (in == NULL || *in == NULL || inSz < 0) {
8238
        WOLFSSL_MSG("Bad argument");
8239
        return NULL;
8240
    }
8241
8242
    if ((out != NULL) && (*out != NULL)) {
8243
        pkey = *out;
8244
    }
8245
8246
#if !defined(NO_RSA)
8247
    if (d2iTryRsaKey(&pkey, *in, inSz, priv) >= 0) {
8248
        ;
8249
    }
8250
    else
8251
#endif /* NO_RSA */
8252
#if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
8253
    if (d2iTryEccKey(&pkey, *in, inSz, priv) >= 0) {
8254
        ;
8255
    }
8256
    else
8257
#endif /* HAVE_ECC && OPENSSL_EXTRA */
8258
#if !defined(NO_DSA)
8259
    if (d2iTryDsaKey(&pkey, *in, inSz, priv) >= 0) {
8260
        ;
8261
    }
8262
    else
8263
#endif /* NO_DSA */
8264
#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
8265
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
8266
    (HAVE_FIPS_VERSION > 2))
8267
    if (d2iTryDhKey(&pkey, *in, inSz, priv) >= 0) {
8268
        ;
8269
    }
8270
    else
8271
#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
8272
#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
8273
8274
#if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA)
8275
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
8276
        (HAVE_FIPS_VERSION > 2))
8277
    if (d2iTryAltDhKey(&pkey, *in, inSz, priv) >= 0) {
8278
        ;
8279
    }
8280
    else
8281
#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
8282
#endif /* !NO_DH &&  OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */
8283
8284
#ifdef HAVE_FALCON
8285
    if (d2iTryFalconKey(&pkey, *in, inSz, priv) >= 0) {
8286
        ;
8287
    }
8288
    else
8289
#endif /* HAVE_FALCON */
8290
#ifdef HAVE_DILITHIUM
8291
    if (d2iTryDilithiumKey(&pkey, *in, inSz, priv) >= 0) {
8292
        ;
8293
    }
8294
    else
8295
#endif /* HAVE_DILITHIUM */
8296
    {
8297
        WOLFSSL_MSG("wolfSSL_d2i_PUBKEY couldn't determine key type");
8298
    }
8299
8300
    if ((pkey != NULL) && (out != NULL)) {
8301
        *out = pkey;
8302
    }
8303
    return pkey;
8304
}
8305
#endif /* OPENSSL_EXTRA || WPA_SMALL */
8306
8307
#ifdef OPENSSL_EXTRA
8308
8309
WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY(
8310
    WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey, const unsigned char** keyBuf,
8311
    long keyLen)
8312
{
8313
    WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL;
8314
#ifdef WOLFSSL_PEM_TO_DER
8315
    int ret;
8316
    DerBuffer* pkcs8Der = NULL;
8317
    DerBuffer rawDer;
8318
    EncryptedInfo info;
8319
    int advanceLen = 0;
8320
8321
    XMEMSET(&info, 0, sizeof(info));
8322
    XMEMSET(&rawDer, 0, sizeof(rawDer));
8323
8324
    if (keyBuf == NULL || *keyBuf == NULL || keyLen <= 0) {
8325
        WOLFSSL_MSG("Bad key PEM/DER args");
8326
        return NULL;
8327
    }
8328
8329
    ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &pkcs8Der, NULL, &info,
8330
                   NULL);
8331
    if (ret < 0) {
8332
        WOLFSSL_MSG("Not PEM format");
8333
        ret = AllocDer(&pkcs8Der, (word32)keyLen, PRIVATEKEY_TYPE, NULL);
8334
        if (ret == 0) {
8335
            XMEMCPY(pkcs8Der->buffer, *keyBuf, keyLen);
8336
        }
8337
    }
8338
    else {
8339
        advanceLen = (int)info.consumed;
8340
    }
8341
8342
    if (ret == 0) {
8343
        /* Verify this is PKCS8 Key */
8344
        word32 inOutIdx = 0;
8345
        word32 algId;
8346
        ret = ToTraditionalInline_ex(pkcs8Der->buffer, &inOutIdx,
8347
                pkcs8Der->length, &algId);
8348
        if (ret >= 0) {
8349
            if (advanceLen == 0) /* Set only if not PEM */
8350
                advanceLen = (int)inOutIdx + ret;
8351
            if (algId == DHk) {
8352
                /* Special case for DH as we expect the DER buffer to be always
8353
                 * be in PKCS8 format */
8354
                rawDer.buffer = pkcs8Der->buffer;
8355
                rawDer.length = inOutIdx + (word32)ret;
8356
            }
8357
            else {
8358
                rawDer.buffer = pkcs8Der->buffer + inOutIdx;
8359
                rawDer.length = (word32)ret;
8360
            }
8361
            ret = 0; /* good DER */
8362
        }
8363
    }
8364
8365
    if (ret == 0) {
8366
        pkcs8 = wolfSSL_EVP_PKEY_new();
8367
        if (pkcs8 == NULL)
8368
            ret = MEMORY_E;
8369
    }
8370
    if (ret == 0) {
8371
        pkcs8->pkey.ptr = (char*)XMALLOC(rawDer.length, NULL,
8372
            DYNAMIC_TYPE_PUBLIC_KEY);
8373
        if (pkcs8->pkey.ptr == NULL)
8374
            ret = MEMORY_E;
8375
    }
8376
    if (ret == 0) {
8377
        XMEMCPY(pkcs8->pkey.ptr, rawDer.buffer, rawDer.length);
8378
        pkcs8->pkey_sz = (int)rawDer.length;
8379
    }
8380
8381
    FreeDer(&pkcs8Der);
8382
    if (ret != 0) {
8383
        wolfSSL_EVP_PKEY_free(pkcs8);
8384
        pkcs8 = NULL;
8385
    }
8386
    else {
8387
        *keyBuf += advanceLen;
8388
    }
8389
    if (pkey != NULL) {
8390
        *pkey = pkcs8;
8391
    }
8392
8393
#else
8394
    (void)bio;
8395
    (void)pkey;
8396
#endif /* WOLFSSL_PEM_TO_DER */
8397
8398
    return pkcs8;
8399
}
8400
8401
#ifdef OPENSSL_ALL
8402
int wolfSSL_i2d_PKCS8_PKEY(WOLFSSL_PKCS8_PRIV_KEY_INFO* key, unsigned char** pp)
8403
{
8404
    word32 keySz = 0;
8405
    unsigned char* out;
8406
    int len;
8407
8408
    WOLFSSL_ENTER("wolfSSL_i2d_PKCS8_PKEY");
8409
8410
    if (key == NULL)
8411
        return WOLFSSL_FATAL_ERROR;
8412
8413
    if (pkcs8_encode(key, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
8414
        return WOLFSSL_FATAL_ERROR;
8415
    len = (int)keySz;
8416
8417
    if ((pp == NULL) || (len == 0))
8418
        return len;
8419
8420
    if (*pp == NULL) {
8421
        out = (unsigned char*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1);
8422
        if (out == NULL)
8423
            return WOLFSSL_FATAL_ERROR;
8424
    }
8425
    else {
8426
        out = *pp;
8427
    }
8428
8429
    if (pkcs8_encode(key, out, &keySz) != len) {
8430
        if (*pp == NULL)
8431
            XFREE(out, NULL, DYNAMIC_TYPE_ASN1);
8432
        return WOLFSSL_FATAL_ERROR;
8433
    }
8434
8435
    if (*pp == NULL)
8436
        *pp = out;
8437
    else
8438
        *pp += len;
8439
8440
    return len;
8441
}
8442
#endif
8443
8444
#ifndef NO_BIO
8445
/* put SSL type in extra for now, not very common */
8446
8447
/* Converts a DER format key read from "bio" to a PKCS8 structure.
8448
 *
8449
 * bio  input bio to read DER from
8450
 * pkey If not NULL then this pointer will be overwritten with a new PKCS8
8451
 *      structure.
8452
 *
8453
 * returns a WOLFSSL_PKCS8_PRIV_KEY_INFO pointer on success and NULL in fail
8454
 *         case.
8455
 */
8456
WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY_bio(WOLFSSL_BIO* bio,
8457
        WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey)
8458
{
8459
    WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL;
8460
#ifdef WOLFSSL_PEM_TO_DER
8461
    unsigned char* mem = NULL;
8462
    int memSz;
8463
8464
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS8_PKEY_bio");
8465
8466
    if (bio == NULL) {
8467
        return NULL;
8468
    }
8469
8470
    if ((memSz = wolfSSL_BIO_get_mem_data(bio, &mem)) < 0) {
8471
        return NULL;
8472
    }
8473
8474
    pkcs8 = wolfSSL_d2i_PKCS8_PKEY(pkey, (const unsigned char**)&mem, memSz);
8475
#else
8476
    (void)bio;
8477
    (void)pkey;
8478
#endif /* WOLFSSL_PEM_TO_DER */
8479
8480
    return pkcs8;
8481
}
8482
8483
8484
/* expecting DER format public key
8485
 *
8486
 * bio  input bio to read DER from
8487
 * out  If not NULL then this pointer will be overwritten with a new
8488
 * WOLFSSL_EVP_PKEY pointer
8489
 *
8490
 * returns a WOLFSSL_EVP_PKEY pointer on success and NULL in fail case.
8491
 */
8492
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio,
8493
                                         WOLFSSL_EVP_PKEY** out)
8494
{
8495
    unsigned char* mem;
8496
    long memSz;
8497
    WOLFSSL_EVP_PKEY* pkey = NULL;
8498
8499
    WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY_bio");
8500
8501
    if (bio == NULL) {
8502
        return NULL;
8503
    }
8504
    (void)out;
8505
8506
    memSz = wolfSSL_BIO_get_len(bio);
8507
    if (memSz <= 0) {
8508
        return NULL;
8509
    }
8510
8511
    mem = (unsigned char*)XMALLOC((size_t)memSz, bio->heap,
8512
                                DYNAMIC_TYPE_TMP_BUFFER);
8513
    if (mem == NULL) {
8514
        return NULL;
8515
    }
8516
8517
    if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) {
8518
        pkey = wolfSSL_d2i_PUBKEY(NULL, (const unsigned char**)&mem, memSz);
8519
        if (out != NULL && pkey != NULL) {
8520
            *out = pkey;
8521
        }
8522
    }
8523
8524
    XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
8525
    return pkey;
8526
}
8527
8528
#endif /* !NO_BIO */
8529
8530
8531
/* Converts a DER encoded public key to a WOLFSSL_EVP_PKEY structure.
8532
 *
8533
 * out  pointer to new WOLFSSL_EVP_PKEY structure. Can be NULL
8534
 * in   DER buffer to convert
8535
 * inSz size of in buffer
8536
 *
8537
 * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL
8538
 *         on fail
8539
 */
8540
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** out,
8541
                                     const unsigned char** in, long inSz)
8542
{
8543
    WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY");
8544
    return d2iGenericKey(out, in, inSz, 0);
8545
}
8546
8547
#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_ASN) && \
8548
    !defined(NO_PWDBASED)
8549
8550
/* helper function to get raw pointer to DER buffer from WOLFSSL_EVP_PKEY */
8551
static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key,
8552
    unsigned char** der)
8553
{
8554
    int sz;
8555
    word16 pkcs8HeaderSz;
8556
8557
    if (!key || !key->pkey_sz)
8558
        return WOLFSSL_FATAL_ERROR;
8559
8560
    /* return the key without PKCS8 for compatibility */
8561
    /* if pkcs8HeaderSz is invalid, use 0 and return all of pkey */
8562
    pkcs8HeaderSz = 0;
8563
    if (key->pkey_sz > key->pkcs8HeaderSz)
8564
        pkcs8HeaderSz = key->pkcs8HeaderSz;
8565
    sz = key->pkey_sz - pkcs8HeaderSz;
8566
    if (der) {
8567
        unsigned char* pt = (unsigned char*)key->pkey.ptr;
8568
        if (*der) {
8569
            /* since this function signature has no size value passed in it is
8570
             * assumed that the user has allocated a large enough buffer */
8571
            XMEMCPY(*der, pt + pkcs8HeaderSz, (size_t)sz);
8572
            *der += sz;
8573
        }
8574
        else {
8575
            *der = (unsigned char*)XMALLOC((size_t)sz, NULL,
8576
                                                DYNAMIC_TYPE_OPENSSL);
8577
            if (*der == NULL) {
8578
                return WOLFSSL_FATAL_ERROR;
8579
            }
8580
            XMEMCPY(*der, pt + pkcs8HeaderSz, (size_t)sz);
8581
        }
8582
    }
8583
    return sz;
8584
}
8585
8586
int wolfSSL_i2d_PUBKEY(const WOLFSSL_EVP_PKEY *key, unsigned char **der)
8587
{
8588
    return wolfSSL_i2d_PublicKey(key, der);
8589
}
8590
8591
#endif /* OPENSSL_EXTRA && !NO_CERTS && !NO_ASN && !NO_PWDBASED */
8592
8593
static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out,
8594
    const unsigned char **in, long inSz, int priv)
8595
{
8596
    int ret = 0;
8597
    word32 idx = 0, algId;
8598
    word16 pkcs8HeaderSz = 0;
8599
    WOLFSSL_EVP_PKEY* local;
8600
    int opt = 0;
8601
8602
    (void)opt;
8603
8604
    if (in == NULL || inSz < 0) {
8605
        WOLFSSL_MSG("Bad argument");
8606
        return NULL;
8607
    }
8608
8609
    if (priv == 1) {
8610
        /* Check if input buffer has PKCS8 header. In the case that it does not
8611
         * have a PKCS8 header then do not error out. */
8612
        if ((ret = ToTraditionalInline_ex((const byte*)(*in), &idx,
8613
                                          (word32)inSz, &algId)) > 0) {
8614
            WOLFSSL_MSG("Found PKCS8 header");
8615
            pkcs8HeaderSz = (word16)idx;
8616
8617
            if ((type == WC_EVP_PKEY_RSA && algId != RSAk
8618
            #ifdef WC_RSA_PSS
8619
                 && algId != RSAPSSk
8620
            #endif
8621
                 ) ||
8622
                (type == WC_EVP_PKEY_EC && algId != ECDSAk) ||
8623
                (type == WC_EVP_PKEY_DSA && algId != DSAk) ||
8624
                (type == WC_EVP_PKEY_DH && algId != DHk)) {
8625
                WOLFSSL_MSG("PKCS8 does not match EVP key type");
8626
                return NULL;
8627
            }
8628
8629
            (void)idx; /* not used */
8630
        }
8631
        else {
8632
            if (ret != WC_NO_ERR_TRACE(ASN_PARSE_E)) {
8633
                WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 "
8634
                    "header");
8635
                return NULL;
8636
            }
8637
        }
8638
    }
8639
8640
    if (out != NULL && *out != NULL) {
8641
        wolfSSL_EVP_PKEY_free(*out);
8642
        *out = NULL;
8643
    }
8644
    local = wolfSSL_EVP_PKEY_new();
8645
    if (local == NULL) {
8646
        return NULL;
8647
    }
8648
8649
    local->type     = type;
8650
    local->pkey_sz  = (int)inSz;
8651
    local->pkcs8HeaderSz = pkcs8HeaderSz;
8652
    local->pkey.ptr = (char*)XMALLOC((size_t)inSz, NULL,
8653
                                        DYNAMIC_TYPE_PUBLIC_KEY);
8654
    if (local->pkey.ptr == NULL) {
8655
        wolfSSL_EVP_PKEY_free(local);
8656
        local = NULL;
8657
        return NULL;
8658
    }
8659
    else {
8660
        XMEMCPY(local->pkey.ptr, *in, (size_t)inSz);
8661
    }
8662
8663
    switch (type) {
8664
#ifndef NO_RSA
8665
        case WC_EVP_PKEY_RSA:
8666
            opt = priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC;
8667
            local->ownRsa = 1;
8668
            local->rsa = wolfssl_rsa_d2i(NULL,
8669
                (const unsigned char*)local->pkey.ptr, local->pkey_sz, opt);
8670
            if (local->rsa == NULL) {
8671
                wolfSSL_EVP_PKEY_free(local);
8672
                return NULL;
8673
            }
8674
            break;
8675
#endif /* NO_RSA */
8676
#ifdef HAVE_ECC
8677
        case WC_EVP_PKEY_EC:
8678
            local->ownEcc = 1;
8679
            local->ecc = wolfSSL_EC_KEY_new();
8680
            if (local->ecc == NULL) {
8681
                wolfSSL_EVP_PKEY_free(local);
8682
                return NULL;
8683
            }
8684
            opt = priv ? WOLFSSL_EC_KEY_LOAD_PRIVATE :
8685
                         WOLFSSL_EC_KEY_LOAD_PUBLIC;
8686
            if (wolfSSL_EC_KEY_LoadDer_ex(local->ecc,
8687
                      (const unsigned char*)local->pkey.ptr, local->pkey_sz,
8688
                      opt)
8689
                      != WOLFSSL_SUCCESS) {
8690
                wolfSSL_EVP_PKEY_free(local);
8691
                return NULL;
8692
            }
8693
            break;
8694
#endif /* HAVE_ECC */
8695
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH)
8696
#ifndef NO_DSA
8697
        case WC_EVP_PKEY_DSA:
8698
            local->ownDsa = 1;
8699
            local->dsa = wolfSSL_DSA_new();
8700
            if (local->dsa == NULL) {
8701
                wolfSSL_EVP_PKEY_free(local);
8702
                return NULL;
8703
            }
8704
            opt = priv ? WOLFSSL_DSA_LOAD_PRIVATE : WOLFSSL_DSA_LOAD_PUBLIC;
8705
            if (wolfSSL_DSA_LoadDer_ex(local->dsa,
8706
                    (const unsigned char*)local->pkey.ptr, local->pkey_sz,
8707
                    opt)
8708
                    != WOLFSSL_SUCCESS) {
8709
                wolfSSL_EVP_PKEY_free(local);
8710
                return NULL;
8711
            }
8712
            break;
8713
#endif /* NO_DSA */
8714
#ifndef NO_DH
8715
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2))
8716
        case WC_EVP_PKEY_DH:
8717
            local->ownDh = 1;
8718
            local->dh = wolfSSL_DH_new();
8719
            if (local->dh == NULL) {
8720
                wolfSSL_EVP_PKEY_free(local);
8721
                return NULL;
8722
            }
8723
            if (wolfSSL_DH_LoadDer(local->dh,
8724
                      (const unsigned char*)local->pkey.ptr, local->pkey_sz)
8725
                      != WOLFSSL_SUCCESS) {
8726
                wolfSSL_EVP_PKEY_free(local);
8727
                return NULL;
8728
            }
8729
            break;
8730
#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
8731
#endif /* HAVE_DH */
8732
#endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH */
8733
        default:
8734
            WOLFSSL_MSG("Unsupported key type");
8735
            wolfSSL_EVP_PKEY_free(local);
8736
            return NULL;
8737
    }
8738
8739
    /* advance pointer with success */
8740
    if (local != NULL) {
8741
        if (local->pkey_sz <= (int)inSz) {
8742
            *in += local->pkey_sz;
8743
        }
8744
8745
        if (out != NULL) {
8746
            *out = local;
8747
        }
8748
    }
8749
8750
    return local;
8751
}
8752
8753
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out,
8754
        const unsigned char **in, long inSz)
8755
{
8756
    WOLFSSL_ENTER("wolfSSL_d2i_PublicKey");
8757
8758
    return _d2i_PublicKey(type, out, in, inSz, 0);
8759
}
8760
/* Reads in a DER format key. If PKCS8 headers are found they are stripped off.
8761
 *
8762
 * type  type of key
8763
 * out   newly created WOLFSSL_EVP_PKEY structure
8764
 * in    pointer to input key DER
8765
 * inSz  size of in buffer
8766
 *
8767
 * On success a non null pointer is returned and the pointer in is advanced the
8768
 * same number of bytes read.
8769
 */
8770
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey(int type, WOLFSSL_EVP_PKEY** out,
8771
        const unsigned char **in, long inSz)
8772
{
8773
    WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey");
8774
8775
    return _d2i_PublicKey(type, out, in, inSz, 1);
8776
}
8777
8778
#ifdef WOLF_PRIVATE_KEY_ID
8779
/* Create an EVP structure for use with crypto callbacks */
8780
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out,
8781
    void* heap, int devId)
8782
{
8783
    WOLFSSL_EVP_PKEY* local;
8784
8785
    if (out != NULL && *out != NULL) {
8786
        wolfSSL_EVP_PKEY_free(*out);
8787
        *out = NULL;
8788
    }
8789
8790
    local = wolfSSL_EVP_PKEY_new_ex(heap);
8791
    if (local == NULL) {
8792
        return NULL;
8793
    }
8794
8795
    local->type     = type;
8796
    local->pkey_sz  = 0;
8797
    local->pkcs8HeaderSz = 0;
8798
8799
    switch (type) {
8800
#ifndef NO_RSA
8801
        case WC_EVP_PKEY_RSA:
8802
        {
8803
            RsaKey* key;
8804
            local->ownRsa = 1;
8805
            local->rsa = wolfSSL_RSA_new_ex(heap, devId);
8806
            if (local->rsa == NULL) {
8807
                wolfSSL_EVP_PKEY_free(local);
8808
                return NULL;
8809
            }
8810
            key = (RsaKey*)local->rsa->internal;
8811
        #ifdef WOLF_CRYPTO_CB
8812
            key->devId = devId;
8813
        #endif
8814
            (void)key;
8815
            local->rsa->inSet = 1;
8816
            break;
8817
        }
8818
#endif /* !NO_RSA */
8819
#ifdef HAVE_ECC
8820
        case WC_EVP_PKEY_EC:
8821
        {
8822
            ecc_key* key;
8823
            local->ownEcc = 1;
8824
            local->ecc = wolfSSL_EC_KEY_new_ex(heap, devId);
8825
            if (local->ecc == NULL) {
8826
                wolfSSL_EVP_PKEY_free(local);
8827
                return NULL;
8828
            }
8829
            key = (ecc_key*)local->ecc->internal;
8830
        #ifdef WOLF_CRYPTO_CB
8831
            key->devId = devId;
8832
        #endif
8833
            key->type = ECC_PRIVATEKEY;
8834
            /* key is required to have a key size / curve set, although
8835
             * actual one used is determined by devId callback function */
8836
            wc_ecc_set_curve(key, ECDHE_SIZE, ECC_CURVE_DEF);
8837
8838
            local->ecc->inSet = 1;
8839
            break;
8840
        }
8841
#endif /* HAVE_ECC */
8842
        default:
8843
            WOLFSSL_MSG("Unsupported private key id type");
8844
            wolfSSL_EVP_PKEY_free(local);
8845
            return NULL;
8846
    }
8847
8848
    if (local != NULL && out != NULL) {
8849
        *out = local;
8850
    }
8851
8852
    return local;
8853
}
8854
#endif /* WOLF_PRIVATE_KEY_ID */
8855
8856
#ifndef NO_CERTS /* // NOLINT(readability-redundant-preprocessor) */
8857
8858
#ifndef NO_CHECK_PRIVATE_KEY
8859
/* Check private against public in certificate for match
8860
 *
8861
 * ssl  WOLFSSL structure to check private key in
8862
 *
8863
 * Returns WOLFSSL_SUCCESS on good private key
8864
 *         WOLFSSL_FAILURE if mismatched. */
8865
int wolfSSL_check_private_key(const WOLFSSL* ssl)
8866
{
8867
    int res = WOLFSSL_SUCCESS;
8868
8869
    if (ssl == NULL) {
8870
        return WOLFSSL_FAILURE;
8871
    }
8872
#ifdef WOLFSSL_DUAL_ALG_CERTS
8873
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8874
    wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
8875
    wolfssl_priv_der_unblind(ssl->buffers.altKey, ssl->buffers.altKeyMask);
8876
#endif
8877
    res = check_cert_key(ssl->buffers.certificate, ssl->buffers.key,
8878
        ssl->buffers.altKey, ssl->heap, ssl->buffers.keyDevId,
8879
        ssl->buffers.keyLabel, ssl->buffers.keyId, ssl->buffers.altKeyDevId,
8880
        ssl->buffers.altKeyLabel, ssl->buffers.altKeyId);
8881
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8882
    if (res == WOLFSSL_SUCCESS) {
8883
        int ret;
8884
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
8885
            (DerBuffer**)&ssl->buffers.keyMask);
8886
        if (ret == 0) {
8887
            ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
8888
                (DerBuffer**)&ssl->buffers.altKeyMask);
8889
        }
8890
        if (ret != 0) {
8891
            res = WOLFSSL_FAILURE;
8892
        }
8893
    }
8894
#endif
8895
#else
8896
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8897
    wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
8898
#endif
8899
    res = check_cert_key(ssl->buffers.certificate, ssl->buffers.key, NULL,
8900
        ssl->heap, ssl->buffers.keyDevId, ssl->buffers.keyLabel,
8901
        ssl->buffers.keyId, INVALID_DEVID, 0, 0);
8902
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8903
    if (res == WOLFSSL_SUCCESS) {
8904
        int ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
8905
            (DerBuffer**)&ssl->buffers.keyMask);
8906
        if (ret != 0) {
8907
            res = WOLFSSL_FAILURE;
8908
        }
8909
    }
8910
#endif
8911
#endif
8912
8913
    return res;
8914
}
8915
#endif /* !NO_CHECK_PRIVATE_KEY */
8916
8917
#endif /* !NO_CERTS */
8918
8919
#endif /* OPENSSL_EXTRA */
8920
8921
#if defined(HAVE_RPK)
8922
/* Confirm that all the byte data in the buffer is unique.
8923
 * return 1 if all the byte data in the buffer is unique, otherwise 0.
8924
 */
8925
static int isArrayUnique(const char* buf, size_t len)
8926
{
8927
    size_t i, j;
8928
    /* check the array is unique */
8929
    for (i = 0; i < len -1; ++i) {
8930
        for (j = i+ 1; j < len; ++j) {
8931
            if (buf[i] == buf[j]) {
8932
                return 0;
8933
            }
8934
        }
8935
    }
8936
    return 1;
8937
}
8938
8939
/* Set user preference for the {client,server}_cert_type extension.
8940
 * Takes byte array containing cert types the caller can provide to its peer.
8941
 * Cert types are in preferred order in the array.
8942
 */
8943
static int set_cert_type(RpkConfig* cfg,
8944
                         int client, const char* buf, int bufLen)
8945
{
8946
    int i;
8947
    byte* certTypeCnt;
8948
    byte* certTypes;
8949
8950
    if (cfg == NULL || bufLen > (client ? MAX_CLIENT_CERT_TYPE_CNT :
8951
                                          MAX_SERVER_CERT_TYPE_CNT)) {
8952
        return BAD_FUNC_ARG;
8953
    }
8954
8955
    if (client) {
8956
        certTypeCnt = &cfg->preferred_ClientCertTypeCnt;
8957
        certTypes   =  cfg->preferred_ClientCertTypes;
8958
    }
8959
    else {
8960
        certTypeCnt = &cfg->preferred_ServerCertTypeCnt;
8961
        certTypes   =  cfg->preferred_ServerCertTypes;
8962
    }
8963
    /* if buf is set to NULL or bufLen is zero, it defaults the setting*/
8964
    if (buf == NULL || bufLen == 0) {
8965
        *certTypeCnt = 1;
8966
        for (i = 0; i < 2; i++)
8967
            certTypes[i] = WOLFSSL_CERT_TYPE_X509;
8968
        return WOLFSSL_SUCCESS;
8969
    }
8970
8971
    if (!isArrayUnique(buf, (size_t)bufLen))
8972
        return BAD_FUNC_ARG;
8973
8974
    for (i = 0; i < bufLen; i++) {
8975
        if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
8976
            return BAD_FUNC_ARG;
8977
        certTypes[i] = (byte)buf[i];
8978
    }
8979
    *certTypeCnt = bufLen;
8980
8981
    return WOLFSSL_SUCCESS;
8982
}
8983
int wolfSSL_set_client_cert_type(WOLFSSL* ssl, const char* buf, int buflen)
8984
{
8985
    if (ssl == NULL)
8986
        return BAD_FUNC_ARG;
8987
    return set_cert_type(&ssl->options.rpkConfig, 1, buf, buflen);
8988
}
8989
int wolfSSL_set_server_cert_type(WOLFSSL* ssl, const char* buf, int buflen)
8990
{
8991
    if (ssl == NULL)
8992
        return BAD_FUNC_ARG;
8993
    return set_cert_type(&ssl->options.rpkConfig, 0, buf, buflen);
8994
}
8995
int wolfSSL_CTX_set_client_cert_type(WOLFSSL_CTX* ctx,
8996
                                     const char* buf, int buflen)
8997
{
8998
    if (ctx == NULL)
8999
        return BAD_FUNC_ARG;
9000
    return set_cert_type(&ctx->rpkConfig, 1, buf, buflen);
9001
}
9002
int wolfSSL_CTX_set_server_cert_type(WOLFSSL_CTX* ctx,
9003
                                     const char* buf, int buflen)
9004
{
9005
    if (ctx == NULL)
9006
        return BAD_FUNC_ARG;
9007
    return set_cert_type(&ctx->rpkConfig, 0, buf, buflen);
9008
}
9009
9010
/* get negotiated certificate type value and return it to the second parameter.
9011
 * cert type value:
9012
 * -1: WOLFSSL_CERT_TYPE_UNKNOWN
9013
 *  0: WOLFSSL_CERT_TYPE_X509
9014
 *  2: WOLFSSL_CERT_TYPE_RPK
9015
 * return WOLFSSL_SUCCESS on success, otherwise negative value.
9016
 * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for
9017
 * cert type.
9018
 */
9019
int wolfSSL_get_negotiated_client_cert_type(WOLFSSL* ssl, int* tp)
9020
{
9021
    int ret = WOLFSSL_SUCCESS;
9022
9023
    if (ssl == NULL || tp == NULL)
9024
        return BAD_FUNC_ARG;
9025
9026
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
9027
        if (ssl->options.rpkState.received_ClientCertTypeCnt == 1)
9028
            *tp = ssl->options.rpkState.received_ClientCertTypes[0];
9029
        else
9030
            *tp = WOLFSSL_CERT_TYPE_UNKNOWN;
9031
    }
9032
    else {
9033
        if (ssl->options.rpkState.sending_ClientCertTypeCnt == 1)
9034
            *tp = ssl->options.rpkState.sending_ClientCertTypes[0];
9035
        else
9036
            *tp = WOLFSSL_CERT_TYPE_UNKNOWN;
9037
    }
9038
    return ret;
9039
}
9040
9041
/* get negotiated certificate type value and return it to the second parameter.
9042
 * cert type value:
9043
 * -1: WOLFSSL_CERT_TYPE_UNKNOWN
9044
 *  0: WOLFSSL_CERT_TYPE_X509
9045
 *  2: WOLFSSL_CERT_TYPE_RPK
9046
 * return WOLFSSL_SUCCESS on success, otherwise negative value.
9047
 * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for
9048
 * cert type.
9049
 */
9050
int wolfSSL_get_negotiated_server_cert_type(WOLFSSL* ssl, int* tp)
9051
{
9052
    int ret = WOLFSSL_SUCCESS;
9053
9054
    if (ssl == NULL || tp == NULL)
9055
        return BAD_FUNC_ARG;
9056
9057
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
9058
        if (ssl->options.rpkState.received_ServerCertTypeCnt == 1)
9059
            *tp = ssl->options.rpkState.received_ServerCertTypes[0];
9060
        else
9061
            *tp = WOLFSSL_CERT_TYPE_UNKNOWN;
9062
    }
9063
    else {
9064
        if (ssl->options.rpkState.sending_ServerCertTypeCnt == 1)
9065
            *tp = ssl->options.rpkState.sending_ServerCertTypes[0];
9066
        else
9067
            *tp = WOLFSSL_CERT_TYPE_UNKNOWN;
9068
    }
9069
    return ret;
9070
}
9071
9072
#endif /* HAVE_RPK */
9073
9074
#ifdef HAVE_ECC
9075
9076
/* Set Temp CTX EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */
9077
int wolfSSL_CTX_SetTmpEC_DHE_Sz(WOLFSSL_CTX* ctx, word16 sz)
9078
0
{
9079
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetTmpEC_DHE_Sz");
9080
9081
0
    if (ctx == NULL)
9082
0
        return BAD_FUNC_ARG;
9083
9084
    /* if 0 then get from loaded private key */
9085
0
    if (sz == 0) {
9086
        /* applies only to ECDSA */
9087
0
        if (ctx->privateKeyType != ecc_dsa_sa_algo)
9088
0
            return WOLFSSL_SUCCESS;
9089
9090
0
        if (ctx->privateKeySz == 0) {
9091
0
            WOLFSSL_MSG("Must set private key/cert first");
9092
0
            return BAD_FUNC_ARG;
9093
0
        }
9094
9095
0
        sz = (word16)ctx->privateKeySz;
9096
0
    }
9097
9098
    /* check size */
9099
#if ECC_MIN_KEY_SZ > 0
9100
    if (sz < ECC_MINSIZE)
9101
        return BAD_FUNC_ARG;
9102
#endif
9103
0
    if (sz > ECC_MAXSIZE)
9104
0
        return BAD_FUNC_ARG;
9105
9106
0
    ctx->eccTempKeySz = sz;
9107
9108
0
    return WOLFSSL_SUCCESS;
9109
0
}
9110
9111
9112
/* Set Temp SSL EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */
9113
int wolfSSL_SetTmpEC_DHE_Sz(WOLFSSL* ssl, word16 sz)
9114
0
{
9115
0
    WOLFSSL_ENTER("wolfSSL_SetTmpEC_DHE_Sz");
9116
9117
0
    if (ssl == NULL)
9118
0
        return BAD_FUNC_ARG;
9119
9120
    /* check size */
9121
#if ECC_MIN_KEY_SZ > 0
9122
    if (sz < ECC_MINSIZE)
9123
        return BAD_FUNC_ARG;
9124
#endif
9125
0
    if (sz > ECC_MAXSIZE)
9126
0
        return BAD_FUNC_ARG;
9127
9128
0
    ssl->eccTempKeySz = sz;
9129
9130
0
    return WOLFSSL_SUCCESS;
9131
0
}
9132
9133
#endif /* HAVE_ECC */
9134
9135
9136
typedef struct {
9137
    byte verifyPeer:1;
9138
    byte verifyNone:1;
9139
    byte failNoCert:1;
9140
    byte failNoCertxPSK:1;
9141
    byte verifyPostHandshake:1;
9142
} SetVerifyOptions;
9143
9144
static SetVerifyOptions ModeToVerifyOptions(int mode)
9145
0
{
9146
0
    SetVerifyOptions opts;
9147
0
    XMEMSET(&opts, 0, sizeof(SetVerifyOptions));
9148
9149
0
    if (mode != WOLFSSL_VERIFY_DEFAULT) {
9150
0
        opts.verifyNone = (mode == WOLFSSL_VERIFY_NONE);
9151
0
        if (!opts.verifyNone) {
9152
0
            opts.verifyPeer =
9153
0
                    (mode & WOLFSSL_VERIFY_PEER) != 0;
9154
0
            opts.failNoCertxPSK =
9155
0
                    (mode & WOLFSSL_VERIFY_FAIL_EXCEPT_PSK) != 0;
9156
0
            opts.failNoCert =
9157
0
                    (mode & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0;
9158
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
9159
            opts.verifyPostHandshake =
9160
                    (mode & WOLFSSL_VERIFY_POST_HANDSHAKE) != 0;
9161
#endif
9162
0
        }
9163
0
    }
9164
9165
0
    return opts;
9166
0
}
9167
9168
WOLFSSL_ABI
9169
void wolfSSL_CTX_set_verify(WOLFSSL_CTX* ctx, int mode, VerifyCallback verify_callback)
9170
28
{
9171
28
    SetVerifyOptions opts;
9172
9173
28
    WOLFSSL_ENTER("wolfSSL_CTX_set_verify");
9174
28
    if (ctx == NULL)
9175
0
        return;
9176
9177
28
    opts = ModeToVerifyOptions(mode);
9178
9179
28
    ctx->verifyNone     = opts.verifyNone;
9180
28
    ctx->verifyPeer     = opts.verifyPeer;
9181
28
    ctx->failNoCert     = opts.failNoCert;
9182
28
    ctx->failNoCertxPSK = opts.failNoCertxPSK;
9183
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
9184
    ctx->verifyPostHandshake = opts.verifyPostHandshake;
9185
#endif
9186
9187
28
    ctx->verifyCallback = verify_callback;
9188
28
}
9189
9190
#ifdef OPENSSL_ALL
9191
void wolfSSL_CTX_set_cert_verify_callback(WOLFSSL_CTX* ctx,
9192
    CertVerifyCallback cb, void* arg)
9193
{
9194
    WOLFSSL_ENTER("wolfSSL_CTX_set_cert_verify_callback");
9195
    if (ctx == NULL)
9196
        return;
9197
9198
    ctx->verifyCertCb = cb;
9199
    ctx->verifyCertCbArg = arg;
9200
}
9201
#endif
9202
9203
9204
void wolfSSL_set_verify(WOLFSSL* ssl, int mode, VerifyCallback verify_callback)
9205
0
{
9206
0
    SetVerifyOptions opts;
9207
9208
0
    WOLFSSL_ENTER("wolfSSL_set_verify");
9209
0
    if (ssl == NULL)
9210
0
        return;
9211
9212
0
    opts = ModeToVerifyOptions(mode);
9213
9214
0
    ssl->options.verifyNone = opts.verifyNone;
9215
0
    ssl->options.verifyPeer = opts.verifyPeer;
9216
0
    ssl->options.failNoCert = opts.failNoCert;
9217
0
    ssl->options.failNoCertxPSK = opts.failNoCertxPSK;
9218
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
9219
    ssl->options.verifyPostHandshake = opts.verifyPostHandshake;
9220
#endif
9221
9222
0
    ssl->verifyCallback = verify_callback;
9223
0
}
9224
9225
void wolfSSL_set_verify_result(WOLFSSL *ssl, long v)
9226
0
{
9227
0
    WOLFSSL_ENTER("wolfSSL_set_verify_result");
9228
9229
0
    if (ssl == NULL)
9230
0
        return;
9231
9232
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
9233
    defined(OPENSSL_ALL)
9234
    ssl->peerVerifyRet = (unsigned long)v;
9235
#else
9236
0
    (void)v;
9237
0
    WOLFSSL_STUB("wolfSSL_set_verify_result");
9238
0
#endif
9239
0
}
9240
9241
#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \
9242
    defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
9243
/* For TLS v1.3 send handshake messages after handshake completes. */
9244
/* Returns 1=WOLFSSL_SUCCESS or 0=WOLFSSL_FAILURE */
9245
int wolfSSL_verify_client_post_handshake(WOLFSSL* ssl)
9246
{
9247
    int ret = wolfSSL_request_certificate(ssl);
9248
    if (ret != WOLFSSL_SUCCESS) {
9249
        if (!IsAtLeastTLSv1_3(ssl->version)) {
9250
            /* specific error of wrong version expected */
9251
            WOLFSSL_ERROR(UNSUPPORTED_PROTO_VERSION);
9252
9253
        }
9254
        else {
9255
            WOLFSSL_ERROR(ret); /* log the error in the error queue */
9256
        }
9257
    }
9258
    return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
9259
}
9260
9261
int wolfSSL_CTX_set_post_handshake_auth(WOLFSSL_CTX* ctx, int val)
9262
{
9263
    int ret = wolfSSL_CTX_allow_post_handshake_auth(ctx);
9264
    if (ret == 0) {
9265
        ctx->postHandshakeAuth = (val != 0);
9266
    }
9267
    return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
9268
}
9269
int wolfSSL_set_post_handshake_auth(WOLFSSL* ssl, int val)
9270
{
9271
    int ret = wolfSSL_allow_post_handshake_auth(ssl);
9272
    if (ret == 0) {
9273
        ssl->options.postHandshakeAuth = (val != 0);
9274
    }
9275
    return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
9276
}
9277
#endif /* OPENSSL_EXTRA && !NO_CERTS && WOLFSSL_TLS13 &&
9278
        * WOLFSSL_POST_HANDSHAKE_AUTH */
9279
9280
/* store user ctx for verify callback */
9281
void wolfSSL_SetCertCbCtx(WOLFSSL* ssl, void* ctx)
9282
0
{
9283
0
    WOLFSSL_ENTER("wolfSSL_SetCertCbCtx");
9284
0
    if (ssl)
9285
0
        ssl->verifyCbCtx = ctx;
9286
0
}
9287
9288
9289
/* store user ctx for verify callback */
9290
void wolfSSL_CTX_SetCertCbCtx(WOLFSSL_CTX* ctx, void* userCtx)
9291
0
{
9292
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetCertCbCtx");
9293
0
    if (ctx)
9294
0
        ctx->verifyCbCtx = userCtx;
9295
0
}
9296
9297
9298
/* store context CA Cache addition callback */
9299
void wolfSSL_CTX_SetCACb(WOLFSSL_CTX* ctx, CallbackCACache cb)
9300
0
{
9301
0
    if (ctx && ctx->cm)
9302
0
        ctx->cm->caCacheCallback = cb;
9303
0
}
9304
9305
9306
#if defined(PERSIST_CERT_CACHE)
9307
9308
#if !defined(NO_FILESYSTEM)
9309
9310
/* Persist cert cache to file */
9311
int wolfSSL_CTX_save_cert_cache(WOLFSSL_CTX* ctx, const char* fname)
9312
{
9313
    WOLFSSL_ENTER("wolfSSL_CTX_save_cert_cache");
9314
9315
    if (ctx == NULL || fname == NULL)
9316
        return BAD_FUNC_ARG;
9317
9318
    return CM_SaveCertCache(ctx->cm, fname);
9319
}
9320
9321
9322
/* Persist cert cache from file */
9323
int wolfSSL_CTX_restore_cert_cache(WOLFSSL_CTX* ctx, const char* fname)
9324
{
9325
    WOLFSSL_ENTER("wolfSSL_CTX_restore_cert_cache");
9326
9327
    if (ctx == NULL || fname == NULL)
9328
        return BAD_FUNC_ARG;
9329
9330
    return CM_RestoreCertCache(ctx->cm, fname);
9331
}
9332
9333
#endif /* NO_FILESYSTEM */
9334
9335
/* Persist cert cache to memory */
9336
int wolfSSL_CTX_memsave_cert_cache(WOLFSSL_CTX* ctx, void* mem,
9337
                                   int sz, int* used)
9338
{
9339
    WOLFSSL_ENTER("wolfSSL_CTX_memsave_cert_cache");
9340
9341
    if (ctx == NULL || mem == NULL || used == NULL || sz <= 0)
9342
        return BAD_FUNC_ARG;
9343
9344
    return CM_MemSaveCertCache(ctx->cm, mem, sz, used);
9345
}
9346
9347
9348
/* Restore cert cache from memory */
9349
int wolfSSL_CTX_memrestore_cert_cache(WOLFSSL_CTX* ctx, const void* mem, int sz)
9350
{
9351
    WOLFSSL_ENTER("wolfSSL_CTX_memrestore_cert_cache");
9352
9353
    if (ctx == NULL || mem == NULL || sz <= 0)
9354
        return BAD_FUNC_ARG;
9355
9356
    return CM_MemRestoreCertCache(ctx->cm, mem, sz);
9357
}
9358
9359
9360
/* get how big the the cert cache save buffer needs to be */
9361
int wolfSSL_CTX_get_cert_cache_memsize(WOLFSSL_CTX* ctx)
9362
{
9363
    WOLFSSL_ENTER("wolfSSL_CTX_get_cert_cache_memsize");
9364
9365
    if (ctx == NULL)
9366
        return BAD_FUNC_ARG;
9367
9368
    return CM_GetCertCacheMemSize(ctx->cm);
9369
}
9370
9371
#endif /* PERSIST_CERT_CACHE */
9372
#endif /* !NO_CERTS */
9373
9374
9375
void wolfSSL_load_error_strings(void)
9376
0
{
9377
    /* compatibility only */
9378
0
}
9379
9380
9381
int wolfSSL_library_init(void)
9382
0
{
9383
0
    WOLFSSL_ENTER("wolfSSL_library_init");
9384
0
    if (wolfSSL_Init() == WOLFSSL_SUCCESS)
9385
0
        return WOLFSSL_SUCCESS;
9386
0
    else
9387
0
        return WOLFSSL_FATAL_ERROR;
9388
0
}
9389
9390
9391
#ifdef HAVE_SECRET_CALLBACK
9392
9393
int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx)
9394
{
9395
    WOLFSSL_ENTER("wolfSSL_set_session_secret_cb");
9396
    if (ssl == NULL)
9397
        return WOLFSSL_FAILURE;
9398
9399
    ssl->sessionSecretCb = cb;
9400
    ssl->sessionSecretCtx = ctx;
9401
    if (cb != NULL) {
9402
        /* If using a pre-set key, assume session resumption. */
9403
        ssl->session->sessionIDSz = 0;
9404
        ssl->options.resuming = 1;
9405
    }
9406
9407
    return WOLFSSL_SUCCESS;
9408
}
9409
9410
int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, TicketParseCb cb,
9411
        void *ctx)
9412
{
9413
    WOLFSSL_ENTER("wolfSSL_set_session_ticket_ext_cb");
9414
    if (ssl == NULL)
9415
        return WOLFSSL_FAILURE;
9416
9417
    ssl->ticketParseCb = cb;
9418
    ssl->ticketParseCtx = ctx;
9419
9420
    return WOLFSSL_SUCCESS;
9421
}
9422
9423
int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx)
9424
{
9425
    WOLFSSL_ENTER("wolfSSL_set_secret_cb");
9426
    if (ssl == NULL)
9427
        return WOLFSSL_FATAL_ERROR;
9428
9429
    ssl->tlsSecretCb = cb;
9430
    ssl->tlsSecretCtx = ctx;
9431
9432
    return WOLFSSL_SUCCESS;
9433
}
9434
9435
#ifdef SHOW_SECRETS
9436
int tlsShowSecrets(WOLFSSL* ssl, void* secret, int secretSz,
9437
        void* ctx)
9438
{
9439
    /* Wireshark Pre-Master-Secret Format:
9440
     *  CLIENT_RANDOM <clientrandom> <mastersecret>
9441
     */
9442
    const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
9443
    int i, pmsPos = 0;
9444
    char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
9445
    byte clientRandom[RAN_LEN];
9446
    int clientRandomSz;
9447
9448
    (void)ctx;
9449
9450
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
9451
        sizeof(clientRandom));
9452
9453
    if (clientRandomSz <= 0) {
9454
        printf("Error getting server random %d\n", clientRandomSz);
9455
        return BAD_FUNC_ARG;
9456
    }
9457
9458
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
9459
        CLIENT_RANDOM_LABEL);
9460
    pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
9461
    for (i = 0; i < clientRandomSz; i++) {
9462
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
9463
            clientRandom[i]);
9464
        pmsPos += 2;
9465
    }
9466
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
9467
    pmsPos += 1;
9468
    for (i = 0; i < secretSz; i++) {
9469
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
9470
            ((byte*)secret)[i]);
9471
        pmsPos += 2;
9472
    }
9473
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
9474
    pmsPos += 1;
9475
9476
    /* print master secret */
9477
    puts(pmsBuf);
9478
9479
    #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
9480
    {
9481
        FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
9482
        if (f != XBADFILE) {
9483
            XFWRITE(pmsBuf, 1, pmsPos, f);
9484
            XFCLOSE(f);
9485
        }
9486
    }
9487
    #endif
9488
    return 0;
9489
}
9490
#endif /* SHOW_SECRETS */
9491
9492
#endif
9493
9494
9495
#ifdef OPENSSL_EXTRA
9496
9497
/*
9498
 * check if the list has TLS13 and pre-TLS13 suites
9499
 * @param list cipher suite list that user want to set
9500
 *         (caller required to check for NULL)
9501
 * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
9502
 */
9503
static int CheckcipherList(const char* list)
9504
{
9505
    int ret;
9506
    int findTLSv13Suites = 0;
9507
    int findbeforeSuites = 0;
9508
    byte cipherSuite0;
9509
    byte cipherSuite1;
9510
    int flags;
9511
    char* next = (char*)list;
9512
9513
    do {
9514
        char*  current = next;
9515
        char   name[MAX_SUITE_NAME + 1];
9516
        word32 length = MAX_SUITE_NAME;
9517
        word32 current_length;
9518
        byte major = INVALID_BYTE;
9519
        byte minor = INVALID_BYTE;
9520
9521
        next   = XSTRSTR(next, ":");
9522
9523
        if (next) {
9524
            current_length = (word32)(next - current);
9525
            ++next; /* increment to skip ':' */
9526
        }
9527
        else {
9528
            current_length = (word32)XSTRLEN(current);
9529
        }
9530
9531
        if (current_length == 0) {
9532
            break;
9533
        }
9534
9535
        if (current_length < length) {
9536
            length = current_length;
9537
        }
9538
        XMEMCPY(name, current, length);
9539
        name[length] = 0;
9540
9541
        if (XSTRCMP(name, "ALL") == 0 ||
9542
            XSTRCMP(name, "DEFAULT") == 0 ||
9543
            XSTRCMP(name, "HIGH") == 0)
9544
        {
9545
            findTLSv13Suites = 1;
9546
            findbeforeSuites = 1;
9547
            break;
9548
        }
9549
9550
        ret = GetCipherSuiteFromName(name, &cipherSuite0,
9551
                &cipherSuite1, &major, &minor, &flags);
9552
        if (ret == 0) {
9553
            if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) {
9554
                /* TLSv13 suite */
9555
                findTLSv13Suites = 1;
9556
            }
9557
            else {
9558
                findbeforeSuites = 1;
9559
            }
9560
        }
9561
9562
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
9563
        /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */
9564
        if (ret != 0) {
9565
            char* subStr = name;
9566
            char* subStrNext;
9567
9568
            do {
9569
                subStrNext = XSTRSTR(subStr, "+");
9570
9571
                if ((XSTRCMP(subStr, "ECDHE") == 0) ||
9572
                    (XSTRCMP(subStr, "RSA") == 0)) {
9573
                    return 0;
9574
                }
9575
9576
                if (subStrNext && (XSTRLEN(subStrNext) > 0)) {
9577
                    subStr = subStrNext + 1; /* +1 to skip past '+' */
9578
                }
9579
            } while (subStrNext != NULL);
9580
        }
9581
    #endif
9582
9583
        if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
9584
            /* list has mixed suites */
9585
            return 0;
9586
        }
9587
    } while (next);
9588
9589
    if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
9590
        ret = 1;/* only before TLSv13 suites */
9591
    }
9592
    else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
9593
        ret = 2;/* only TLSv13 suties */
9594
    }
9595
    else {
9596
        ret = 0;/* handle as mixed */
9597
    }
9598
    return ret;
9599
}
9600
9601
/* parse some bulk lists like !eNULL / !aNULL
9602
 *
9603
 * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
9604
 */
9605
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
9606
        Suites* suites, const char* list)
9607
{
9608
    int     ret = 0;
9609
    int     listattribute = 0;
9610
    int     tls13Only = 0;
9611
    WC_DECLARE_VAR(suitesCpy, byte, WOLFSSL_MAX_SUITE_SZ, 0);
9612
    word16  suitesCpySz = 0;
9613
    word16  i = 0;
9614
    word16  j = 0;
9615
9616
    if (suites == NULL || list == NULL) {
9617
        WOLFSSL_MSG("NULL argument");
9618
        return WOLFSSL_FAILURE;
9619
    }
9620
9621
    listattribute = CheckcipherList(list);
9622
9623
    if (listattribute == 0) {
9624
       /* list has mixed(pre-TLSv13 and TLSv13) suites
9625
        * update cipher suites the same as before
9626
        */
9627
        return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS :
9628
        WOLFSSL_FAILURE;
9629
    }
9630
    else if (listattribute == 1) {
9631
       /* list has only pre-TLSv13 suites.
9632
        * Only update before TLSv13 suites.
9633
        */
9634
        tls13Only = 0;
9635
    }
9636
    else if (listattribute == 2) {
9637
       /* list has only TLSv13 suites. Only update TLv13 suites
9638
        * simulate set_ciphersuites() compatibility layer API
9639
        */
9640
        tls13Only = 1;
9641
        if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) ||
9642
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) {
9643
            /* Silently ignore TLS 1.3 ciphers if we don't support it. */
9644
            return WOLFSSL_SUCCESS;
9645
        }
9646
    }
9647
9648
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
9649
#ifdef WOLFSSL_SMALL_STACK
9650
    if (suites->suiteSz > 0) {
9651
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
9652
                DYNAMIC_TYPE_TMP_BUFFER);
9653
        if (suitesCpy == NULL) {
9654
            return WOLFSSL_FAILURE;
9655
        }
9656
9657
        XMEMSET(suitesCpy, 0, suites->suiteSz);
9658
    }
9659
#else
9660
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
9661
#endif
9662
9663
    if (suites->suiteSz > 0)
9664
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
9665
    suitesCpySz = suites->suiteSz;
9666
9667
    ret = SetCipherList_ex(ctx, ssl, suites, list);
9668
    if (ret != 1) {
9669
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
9670
        return WOLFSSL_FAILURE;
9671
    }
9672
9673
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
9674
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
9675
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
9676
     * Since we direct both API here we attempt to provide API compatibility. If
9677
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
9678
     * suites and keep the suites from the other group. */
9679
    for (i = 0; i < suitesCpySz &&
9680
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
9681
        /* Check for duplicates */
9682
        int duplicate = 0;
9683
        for (j = 0; j < suites->suiteSz; j += 2) {
9684
            if (suitesCpy[i] == suites->suites[j] &&
9685
                    suitesCpy[i+1] == suites->suites[j+1]) {
9686
                duplicate = 1;
9687
                break;
9688
            }
9689
        }
9690
        if (!duplicate) {
9691
            if (tls13Only) {
9692
                /* Updating TLS 1.3 ciphers */
9693
                if (suitesCpy[i] != TLS13_BYTE) {
9694
                    /* Only copy over <= TLS 1.2 ciphers */
9695
                    /* TLS 1.3 ciphers take precedence */
9696
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
9697
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
9698
                }
9699
            }
9700
            else {
9701
                /* Updating <= TLS 1.2 ciphers */
9702
                if (suitesCpy[i] == TLS13_BYTE) {
9703
                    /* Only copy over TLS 1.3 ciphers */
9704
                    /* TLS 1.3 ciphers take precedence */
9705
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
9706
                             suites->suiteSz);
9707
                    suites->suites[0] = suitesCpy[i];
9708
                    suites->suites[1] = suitesCpy[i+1];
9709
                    suites->suiteSz += 2;
9710
                }
9711
            }
9712
        }
9713
    }
9714
9715
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
9716
    return ret;
9717
}
9718
9719
#endif
9720
9721
9722
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
9723
0
{
9724
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
9725
9726
0
    if (ctx == NULL)
9727
0
        return WOLFSSL_FAILURE;
9728
9729
0
    if (AllocateCtxSuites(ctx) != 0)
9730
0
        return WOLFSSL_FAILURE;
9731
9732
#ifdef OPENSSL_EXTRA
9733
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
9734
#else
9735
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
9736
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
9737
0
#endif
9738
0
}
9739
9740
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
9741
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
9742
                                      const int listSz)
9743
{
9744
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
9745
9746
    if (ctx == NULL)
9747
        return WOLFSSL_FAILURE;
9748
9749
    if (AllocateCtxSuites(ctx) != 0)
9750
        return WOLFSSL_FAILURE;
9751
9752
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
9753
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
9754
}
9755
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
9756
9757
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
9758
0
{
9759
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
9760
9761
0
    if (ssl == NULL || ssl->ctx == NULL) {
9762
0
        return WOLFSSL_FAILURE;
9763
0
    }
9764
9765
0
    if (AllocateSuites(ssl) != 0)
9766
0
        return WOLFSSL_FAILURE;
9767
9768
#ifdef OPENSSL_EXTRA
9769
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
9770
#else
9771
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
9772
0
        WOLFSSL_SUCCESS :
9773
0
        WOLFSSL_FAILURE;
9774
0
#endif
9775
0
}
9776
9777
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
9778
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
9779
                                  const int listSz)
9780
{
9781
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
9782
9783
    if (ssl == NULL || ssl->ctx == NULL) {
9784
        return WOLFSSL_FAILURE;
9785
    }
9786
9787
    if (AllocateSuites(ssl) != 0)
9788
        return WOLFSSL_FAILURE;
9789
9790
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
9791
           ? WOLFSSL_SUCCESS
9792
           : WOLFSSL_FAILURE;
9793
}
9794
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
9795
9796
9797
#ifdef HAVE_KEYING_MATERIAL
9798
9799
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
9800
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
9801
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
9802
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
9803
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
9804
9805
static const struct ForbiddenLabels {
9806
    const char* label;
9807
    size_t labelLen;
9808
} forbiddenLabels[] = {
9809
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
9810
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
9811
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
9812
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
9813
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
9814
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
9815
    {NULL, 0},
9816
};
9817
9818
/**
9819
 * Implement RFC 5705
9820
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
9821
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
9822
 */
9823
int wolfSSL_export_keying_material(WOLFSSL *ssl,
9824
        unsigned char *out, size_t outLen,
9825
        const char *label, size_t labelLen,
9826
        const unsigned char *context, size_t contextLen,
9827
        int use_context)
9828
{
9829
    byte*  seed = NULL;
9830
    word32 seedLen;
9831
    const struct ForbiddenLabels* fl;
9832
9833
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
9834
9835
    if (ssl == NULL || out == NULL || label == NULL ||
9836
            (use_context && contextLen && context == NULL)) {
9837
        WOLFSSL_MSG("Bad argument");
9838
        return WOLFSSL_FAILURE;
9839
    }
9840
9841
    /* clientRandom + serverRandom
9842
     * OR
9843
     * clientRandom + serverRandom + ctx len encoding + ctx */
9844
    seedLen = !use_context ? (word32)SEED_LEN :
9845
                             (word32)SEED_LEN + 2 + (word32)contextLen;
9846
9847
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
9848
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
9849
                    "data. Call wolfSSL_KeepArrays before attempting to "
9850
                    "export keyid material.");
9851
        return WOLFSSL_FAILURE;
9852
    }
9853
9854
    /* check forbidden labels */
9855
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
9856
        if (labelLen >= fl->labelLen &&
9857
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
9858
            WOLFSSL_MSG("Forbidden label");
9859
            return WOLFSSL_FAILURE;
9860
        }
9861
    }
9862
9863
#ifdef WOLFSSL_TLS13
9864
    if (IsAtLeastTLSv1_3(ssl->version)) {
9865
        /* Path for TLS 1.3 */
9866
        if (!use_context) {
9867
            contextLen = 0;
9868
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
9869
        }
9870
9871
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
9872
                context, contextLen) != 0) {
9873
            WOLFSSL_MSG("Tls13_Exporter error");
9874
            return WOLFSSL_FAILURE;
9875
        }
9876
        return WOLFSSL_SUCCESS;
9877
    }
9878
#endif
9879
9880
    /* Path for <=TLS 1.2 */
9881
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
9882
    if (seed == NULL) {
9883
        WOLFSSL_MSG("malloc error");
9884
        return WOLFSSL_FAILURE;
9885
    }
9886
9887
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
9888
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
9889
9890
    if (use_context) {
9891
        /* Encode len in big endian */
9892
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
9893
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
9894
        if (contextLen) {
9895
            /* 0 length context is allowed */
9896
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
9897
        }
9898
    }
9899
9900
    PRIVATE_KEY_UNLOCK();
9901
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
9902
            (byte*)label, (word32)labelLen, seed, seedLen,
9903
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
9904
            ssl->devId) != 0) {
9905
        WOLFSSL_MSG("wc_PRF_TLS error");
9906
        PRIVATE_KEY_LOCK();
9907
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
9908
        return WOLFSSL_FAILURE;
9909
    }
9910
    PRIVATE_KEY_LOCK();
9911
9912
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
9913
    return WOLFSSL_SUCCESS;
9914
}
9915
#endif /* HAVE_KEYING_MATERIAL */
9916
9917
int wolfSSL_dtls_get_using_nonblock(WOLFSSL* ssl)
9918
0
{
9919
0
    int useNb = 0;
9920
9921
0
    if (ssl == NULL)
9922
0
        return WOLFSSL_FAILURE;
9923
9924
0
    WOLFSSL_ENTER("wolfSSL_dtls_get_using_nonblock");
9925
0
    if (ssl->options.dtls) {
9926
#ifdef WOLFSSL_DTLS
9927
        useNb = ssl->options.dtlsUseNonblock;
9928
#endif
9929
0
    }
9930
0
    else {
9931
0
        WOLFSSL_MSG("wolfSSL_dtls_get_using_nonblock() is "
9932
0
                    "DEPRECATED for non-DTLS use.");
9933
0
    }
9934
0
    return useNb;
9935
0
}
9936
9937
9938
#ifndef WOLFSSL_LEANPSK
9939
9940
void wolfSSL_dtls_set_using_nonblock(WOLFSSL* ssl, int nonblock)
9941
0
{
9942
0
    (void)nonblock;
9943
9944
0
    WOLFSSL_ENTER("wolfSSL_dtls_set_using_nonblock");
9945
9946
0
    if (ssl == NULL)
9947
0
        return;
9948
9949
0
    if (ssl->options.dtls) {
9950
#ifdef WOLFSSL_DTLS
9951
        ssl->options.dtlsUseNonblock = (nonblock != 0);
9952
#endif
9953
0
    }
9954
0
    else {
9955
0
        WOLFSSL_MSG("wolfSSL_dtls_set_using_nonblock() is "
9956
0
                    "DEPRECATED for non-DTLS use.");
9957
0
    }
9958
0
}
9959
9960
9961
#ifdef WOLFSSL_DTLS
9962
9963
int wolfSSL_dtls_get_current_timeout(WOLFSSL* ssl)
9964
{
9965
    int timeout = 0;
9966
    if (ssl)
9967
        timeout = ssl->dtls_timeout;
9968
9969
    WOLFSSL_LEAVE("wolfSSL_dtls_get_current_timeout", timeout);
9970
    return timeout;
9971
}
9972
9973
#ifdef WOLFSSL_DTLS13
9974
9975
/*
9976
 * This API returns 1 when the user should set a short timeout for receiving
9977
 * data. It is recommended that it is at most 1/4 the value returned by
9978
 * wolfSSL_dtls_get_current_timeout().
9979
 */
9980
int wolfSSL_dtls13_use_quick_timeout(WOLFSSL* ssl)
9981
{
9982
    return ssl->dtls13FastTimeout;
9983
}
9984
9985
/*
9986
 * When this is set, a DTLS 1.3 connection will send acks immediately when a
9987
 * disruption is detected to shortcut timeouts. This results in potentially
9988
 * more traffic but may make the handshake quicker.
9989
 */
9990
void wolfSSL_dtls13_set_send_more_acks(WOLFSSL* ssl, int value)
9991
{
9992
    if (ssl != NULL)
9993
        ssl->options.dtls13SendMoreAcks = !!value;
9994
}
9995
#endif /* WOLFSSL_DTLS13 */
9996
9997
int wolfSSL_DTLSv1_get_timeout(WOLFSSL* ssl, WOLFSSL_TIMEVAL* timeleft)
9998
{
9999
    if (ssl && timeleft) {
10000
        XMEMSET(timeleft, 0, sizeof(WOLFSSL_TIMEVAL));
10001
        timeleft->tv_sec = ssl->dtls_timeout;
10002
    }
10003
    return 0;
10004
}
10005
10006
#ifndef NO_WOLFSSL_STUB
10007
int wolfSSL_DTLSv1_handle_timeout(WOLFSSL* ssl)
10008
{
10009
    WOLFSSL_STUB("SSL_DTLSv1_handle_timeout");
10010
    (void)ssl;
10011
    return 0;
10012
}
10013
#endif
10014
10015
#ifndef NO_WOLFSSL_STUB
10016
void wolfSSL_DTLSv1_set_initial_timeout_duration(WOLFSSL* ssl,
10017
    word32 duration_ms)
10018
{
10019
    WOLFSSL_STUB("SSL_DTLSv1_set_initial_timeout_duration");
10020
    (void)ssl;
10021
    (void)duration_ms;
10022
}
10023
#endif
10024
10025
/* user may need to alter init dtls recv timeout, WOLFSSL_SUCCESS on ok */
10026
int wolfSSL_dtls_set_timeout_init(WOLFSSL* ssl, int timeout)
10027
{
10028
    if (ssl == NULL || timeout < 0)
10029
        return BAD_FUNC_ARG;
10030
10031
    if (timeout > ssl->dtls_timeout_max) {
10032
        WOLFSSL_MSG("Can't set dtls timeout init greater than dtls timeout "
10033
                    "max");
10034
        return BAD_FUNC_ARG;
10035
    }
10036
10037
    ssl->dtls_timeout_init = timeout;
10038
    ssl->dtls_timeout = timeout;
10039
10040
    return WOLFSSL_SUCCESS;
10041
}
10042
10043
10044
/* user may need to alter max dtls recv timeout, WOLFSSL_SUCCESS on ok */
10045
int wolfSSL_dtls_set_timeout_max(WOLFSSL* ssl, int timeout)
10046
{
10047
    if (ssl == NULL || timeout < 0)
10048
        return BAD_FUNC_ARG;
10049
10050
    if (timeout < ssl->dtls_timeout_init) {
10051
        WOLFSSL_MSG("Can't set dtls timeout max less than dtls timeout init");
10052
        return BAD_FUNC_ARG;
10053
    }
10054
10055
    ssl->dtls_timeout_max = timeout;
10056
10057
    return WOLFSSL_SUCCESS;
10058
}
10059
10060
10061
int wolfSSL_dtls_got_timeout(WOLFSSL* ssl)
10062
{
10063
    int result = WOLFSSL_SUCCESS;
10064
    WOLFSSL_ENTER("wolfSSL_dtls_got_timeout");
10065
10066
    if (ssl == NULL || !ssl->options.dtls)
10067
        return WOLFSSL_FATAL_ERROR;
10068
10069
#ifdef WOLFSSL_DTLS13
10070
    if (IsAtLeastTLSv1_3(ssl->version)) {
10071
        result = Dtls13RtxTimeout(ssl);
10072
        if (result < 0) {
10073
            if (result == WC_NO_ERR_TRACE(WANT_WRITE))
10074
                ssl->dtls13SendingAckOrRtx = 1;
10075
            ssl->error = result;
10076
            WOLFSSL_ERROR(result);
10077
            return WOLFSSL_FATAL_ERROR;
10078
        }
10079
10080
        return WOLFSSL_SUCCESS;
10081
    }
10082
#endif /* WOLFSSL_DTLS13 */
10083
10084
    /* Do we have any 1.2 messages stored? */
10085
    if (ssl->dtls_tx_msg_list != NULL || ssl->dtls_tx_msg != NULL) {
10086
        if (DtlsMsgPoolTimeout(ssl) < 0){
10087
            ssl->error = SOCKET_ERROR_E;
10088
            WOLFSSL_ERROR(ssl->error);
10089
            result = WOLFSSL_FATAL_ERROR;
10090
        }
10091
        else if ((result = DtlsMsgPoolSend(ssl, 0)) < 0)  {
10092
            ssl->error = result;
10093
            WOLFSSL_ERROR(result);
10094
            result = WOLFSSL_FATAL_ERROR;
10095
        }
10096
        else {
10097
            /* Reset return value to success */
10098
            result = WOLFSSL_SUCCESS;
10099
        }
10100
    }
10101
10102
    WOLFSSL_LEAVE("wolfSSL_dtls_got_timeout", result);
10103
    return result;
10104
}
10105
10106
10107
/* retransmit all the saves messages, WOLFSSL_SUCCESS on ok */
10108
int wolfSSL_dtls_retransmit(WOLFSSL* ssl)
10109
{
10110
    WOLFSSL_ENTER("wolfSSL_dtls_retransmit");
10111
10112
    if (ssl == NULL)
10113
        return WOLFSSL_FATAL_ERROR;
10114
10115
    if (!ssl->options.handShakeDone) {
10116
        int result;
10117
#ifdef WOLFSSL_DTLS13
10118
        if (IsAtLeastTLSv1_3(ssl->version))
10119
            result = Dtls13DoScheduledWork(ssl);
10120
        else
10121
#endif
10122
            result = DtlsMsgPoolSend(ssl, 0);
10123
        if (result < 0) {
10124
            ssl->error = result;
10125
            WOLFSSL_ERROR(result);
10126
            return WOLFSSL_FATAL_ERROR;
10127
        }
10128
    }
10129
10130
    return WOLFSSL_SUCCESS;
10131
}
10132
10133
#endif /* DTLS */
10134
#endif /* LEANPSK */
10135
10136
10137
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
10138
10139
/* Not an SSL function, return 0 for success, error code otherwise */
10140
/* Prereq: ssl's RNG needs to be initialized. */
10141
int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl,
10142
                                 const byte* secret, word32 secretSz)
10143
{
10144
    int ret = 0;
10145
10146
    WOLFSSL_ENTER("wolfSSL_DTLS_SetCookieSecret");
10147
10148
    if (ssl == NULL) {
10149
        WOLFSSL_MSG("need a SSL object");
10150
        return BAD_FUNC_ARG;
10151
    }
10152
10153
    if (secret != NULL && secretSz == 0) {
10154
        WOLFSSL_MSG("can't have a new secret without a size");
10155
        return BAD_FUNC_ARG;
10156
    }
10157
10158
    /* If secretSz is 0, use the default size. */
10159
    if (secretSz == 0)
10160
        secretSz = COOKIE_SECRET_SZ;
10161
10162
    if (secretSz != ssl->buffers.dtlsCookieSecret.length) {
10163
        byte* newSecret;
10164
10165
        if (ssl->buffers.dtlsCookieSecret.buffer != NULL) {
10166
            ForceZero(ssl->buffers.dtlsCookieSecret.buffer,
10167
                      ssl->buffers.dtlsCookieSecret.length);
10168
            XFREE(ssl->buffers.dtlsCookieSecret.buffer,
10169
                  ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
10170
        }
10171
10172
        newSecret = (byte*)XMALLOC(secretSz, ssl->heap,DYNAMIC_TYPE_COOKIE_PWD);
10173
        if (newSecret == NULL) {
10174
            ssl->buffers.dtlsCookieSecret.buffer = NULL;
10175
            ssl->buffers.dtlsCookieSecret.length = 0;
10176
            WOLFSSL_MSG("couldn't allocate new cookie secret");
10177
            return MEMORY_ERROR;
10178
        }
10179
        ssl->buffers.dtlsCookieSecret.buffer = newSecret;
10180
        ssl->buffers.dtlsCookieSecret.length = secretSz;
10181
    #ifdef WOLFSSL_CHECK_MEM_ZERO
10182
        wc_MemZero_Add("wolfSSL_DTLS_SetCookieSecret secret",
10183
            ssl->buffers.dtlsCookieSecret.buffer,
10184
            ssl->buffers.dtlsCookieSecret.length);
10185
    #endif
10186
    }
10187
10188
    /* If the supplied secret is NULL, randomly generate a new secret. */
10189
    if (secret == NULL) {
10190
        ret = wc_RNG_GenerateBlock(ssl->rng,
10191
                             ssl->buffers.dtlsCookieSecret.buffer, secretSz);
10192
    }
10193
    else
10194
        XMEMCPY(ssl->buffers.dtlsCookieSecret.buffer, secret, secretSz);
10195
10196
    WOLFSSL_LEAVE("wolfSSL_DTLS_SetCookieSecret", 0);
10197
    return ret;
10198
}
10199
10200
#endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
10201
10202
10203
/* EITHER SIDE METHODS */
10204
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
10205
    WOLFSSL_METHOD* wolfSSLv23_method(void)
10206
    {
10207
        return wolfSSLv23_method_ex(NULL);
10208
    }
10209
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
10210
    {
10211
        WOLFSSL_METHOD* m = NULL;
10212
        WOLFSSL_ENTER("wolfSSLv23_method");
10213
    #if !defined(NO_WOLFSSL_CLIENT)
10214
        m = wolfSSLv23_client_method_ex(heap);
10215
    #elif !defined(NO_WOLFSSL_SERVER)
10216
        m = wolfSSLv23_server_method_ex(heap);
10217
    #else
10218
        (void)heap;
10219
    #endif
10220
        if (m != NULL) {
10221
            m->side = WOLFSSL_NEITHER_END;
10222
        }
10223
10224
        return m;
10225
    }
10226
10227
    #ifndef NO_OLD_TLS
10228
    #ifdef WOLFSSL_ALLOW_SSLV3
10229
    WOLFSSL_METHOD* wolfSSLv3_method(void)
10230
    {
10231
        return wolfSSLv3_method_ex(NULL);
10232
    }
10233
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
10234
    {
10235
        WOLFSSL_METHOD* m = NULL;
10236
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
10237
    #if !defined(NO_WOLFSSL_CLIENT)
10238
        m = wolfSSLv3_client_method_ex(heap);
10239
    #elif !defined(NO_WOLFSSL_SERVER)
10240
        m = wolfSSLv3_server_method_ex(heap);
10241
    #endif
10242
        if (m != NULL) {
10243
            m->side = WOLFSSL_NEITHER_END;
10244
        }
10245
10246
        return m;
10247
    }
10248
    #endif
10249
    #endif
10250
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
10251
10252
/* client only parts */
10253
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
10254
10255
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
10256
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
10257
    {
10258
        WOLFSSL_STUB("wolfSSLv2_client_method");
10259
        return NULL;
10260
    }
10261
    #endif
10262
10263
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
10264
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
10265
    {
10266
        return wolfSSLv3_client_method_ex(NULL);
10267
    }
10268
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
10269
    {
10270
        WOLFSSL_METHOD* method =
10271
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
10272
                                                     heap, DYNAMIC_TYPE_METHOD);
10273
        (void)heap;
10274
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
10275
        if (method)
10276
            InitSSL_Method(method, MakeSSLv3());
10277
        return method;
10278
    }
10279
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
10280
10281
10282
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
10283
0
    {
10284
0
        return wolfSSLv23_client_method_ex(NULL);
10285
0
    }
10286
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
10287
0
    {
10288
0
        WOLFSSL_METHOD* method =
10289
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
10290
0
                                                     heap, DYNAMIC_TYPE_METHOD);
10291
0
        (void)heap;
10292
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
10293
0
        if (method) {
10294
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
10295
0
        defined(WOLFSSL_SHA512)
10296
0
        #if defined(WOLFSSL_TLS13)
10297
0
            InitSSL_Method(method, MakeTLSv1_3());
10298
        #elif !defined(WOLFSSL_NO_TLS12)
10299
            InitSSL_Method(method, MakeTLSv1_2());
10300
        #elif !defined(NO_OLD_TLS)
10301
            InitSSL_Method(method, MakeTLSv1_1());
10302
        #endif
10303
    #else
10304
        #ifndef NO_OLD_TLS
10305
            InitSSL_Method(method, MakeTLSv1_1());
10306
        #endif
10307
    #endif
10308
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
10309
0
            method->downgrade = 1;
10310
0
    #endif
10311
0
        }
10312
0
        return method;
10313
0
    }
10314
10315
    /* please see note at top of README if you get an error from connect */
10316
    WOLFSSL_ABI
10317
    int wolfSSL_connect(WOLFSSL* ssl)
10318
    {
10319
    #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
10320
          defined(WOLFSSL_TLS13))
10321
        int neededState;
10322
        byte advanceState;
10323
    #endif
10324
        int ret = 0;
10325
10326
        (void)ret;
10327
10328
        #ifdef HAVE_ERRNO_H
10329
            errno = 0;
10330
        #endif
10331
10332
        if (ssl == NULL)
10333
            return BAD_FUNC_ARG;
10334
10335
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
10336
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
10337
            ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
10338
            if (ssl->error != WOLFSSL_SUCCESS) {
10339
                WOLFSSL_ERROR(ssl->error);
10340
                return WOLFSSL_FATAL_ERROR;
10341
            }
10342
            ssl->error = 0; /* expected to be zero here */
10343
        }
10344
10345
    #ifdef OPENSSL_EXTRA
10346
        if (ssl->CBIS != NULL) {
10347
            ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS);
10348
            ssl->cbmode = WOLFSSL_CB_WRITE;
10349
        }
10350
    #endif
10351
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
10352
10353
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
10354
        defined(WOLFSSL_TLS13)
10355
        return wolfSSL_connect_TLSv13(ssl);
10356
    #else
10357
        #ifdef WOLFSSL_TLS13
10358
        if (ssl->options.tls1_3) {
10359
            WOLFSSL_MSG("TLS 1.3");
10360
            return wolfSSL_connect_TLSv13(ssl);
10361
        }
10362
        #endif
10363
10364
        WOLFSSL_MSG("TLS 1.2 or lower");
10365
        WOLFSSL_ENTER("wolfSSL_connect");
10366
10367
        /* make sure this wolfSSL object has arrays and rng setup. Protects
10368
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
10369
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
10370
            return ret;
10371
        }
10372
10373
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
10374
        if ((ssl->ConnectFilter != NULL) &&
10375
            (ssl->options.connectState == CONNECT_BEGIN)) {
10376
            wolfSSL_netfilter_decision_t res;
10377
            if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
10378
                 WOLFSSL_SUCCESS) &&
10379
                (res == WOLFSSL_NETFILTER_REJECT)) {
10380
                ssl->error = SOCKET_FILTERED_E;
10381
                WOLFSSL_ERROR(ssl->error);
10382
                return WOLFSSL_FATAL_ERROR;
10383
            }
10384
        }
10385
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
10386
10387
        if (ssl->options.side != WOLFSSL_CLIENT_END) {
10388
            ssl->error = SIDE_ERROR;
10389
            WOLFSSL_ERROR(ssl->error);
10390
            return WOLFSSL_FATAL_ERROR;
10391
        }
10392
10393
        #ifdef WOLFSSL_DTLS
10394
        if (ssl->version.major == DTLS_MAJOR) {
10395
            ssl->options.dtls   = 1;
10396
            ssl->options.tls    = 1;
10397
            ssl->options.tls1_1 = 1;
10398
            ssl->options.dtlsStateful = 1;
10399
        }
10400
        #endif
10401
10402
        /* fragOffset is non-zero when sending fragments. On the last
10403
         * fragment, fragOffset is zero again, and the state can be
10404
         * advanced. */
10405
        advanceState = ssl->fragOffset == 0 &&
10406
            (ssl->options.connectState == CONNECT_BEGIN ||
10407
             ssl->options.connectState == HELLO_AGAIN ||
10408
             (ssl->options.connectState >= FIRST_REPLY_DONE &&
10409
              ssl->options.connectState <= FIRST_REPLY_FOURTH));
10410
10411
#ifdef WOLFSSL_DTLS13
10412
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
10413
            advanceState = advanceState && !ssl->dtls13SendingAckOrRtx;
10414
#endif /* WOLFSSL_DTLS13 */
10415
10416
        if (ssl->buffers.outputBuffer.length > 0
10417
        #ifdef WOLFSSL_ASYNC_CRYPT
10418
            /* do not send buffered or advance state if last error was an
10419
                async pending operation */
10420
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
10421
        #endif
10422
        ) {
10423
            ret = SendBuffered(ssl);
10424
            if (ret == 0) {
10425
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
10426
                    if (advanceState) {
10427
                        ssl->options.connectState++;
10428
                        WOLFSSL_MSG("connect state: Advanced from last "
10429
                                    "buffered fragment send");
10430
                    #ifdef WOLFSSL_ASYNC_IO
10431
                        /* Cleanup async */
10432
                        FreeAsyncCtx(ssl, 0);
10433
                    #endif
10434
                    }
10435
                }
10436
                else {
10437
                    WOLFSSL_MSG("connect state: "
10438
                                "Not advanced, more fragments to send");
10439
                }
10440
            }
10441
            else {
10442
                ssl->error = ret;
10443
                WOLFSSL_ERROR(ssl->error);
10444
                return WOLFSSL_FATAL_ERROR;
10445
            }
10446
#ifdef WOLFSSL_DTLS13
10447
            if (ssl->options.dtls)
10448
                ssl->dtls13SendingAckOrRtx = 0;
10449
#endif /* WOLFSSL_DTLS13 */
10450
        }
10451
10452
        ret = RetrySendAlert(ssl);
10453
        if (ret != 0) {
10454
            ssl->error = ret;
10455
            WOLFSSL_ERROR(ssl->error);
10456
            return WOLFSSL_FATAL_ERROR;
10457
        }
10458
10459
        switch (ssl->options.connectState) {
10460
10461
        case CONNECT_BEGIN :
10462
            /* always send client hello first */
10463
            if ( (ssl->error = SendClientHello(ssl)) != 0) {
10464
                WOLFSSL_ERROR(ssl->error);
10465
                return WOLFSSL_FATAL_ERROR;
10466
            }
10467
            ssl->options.connectState = CLIENT_HELLO_SENT;
10468
            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
10469
            FALL_THROUGH;
10470
10471
        case CLIENT_HELLO_SENT :
10472
            neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
10473
                                          SERVER_HELLODONE_COMPLETE;
10474
            #ifdef WOLFSSL_DTLS
10475
                /* In DTLS, when resuming, we can go straight to FINISHED,
10476
                 * or do a cookie exchange and then skip to FINISHED, assume
10477
                 * we need the cookie exchange first. */
10478
                if (IsDtlsNotSctpMode(ssl))
10479
                    neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
10480
            #endif
10481
            /* get response */
10482
            WOLFSSL_MSG("Server state up to needed state.");
10483
            while (ssl->options.serverState < neededState) {
10484
                WOLFSSL_MSG("Progressing server state...");
10485
                #ifdef WOLFSSL_TLS13
10486
                    if (ssl->options.tls1_3)
10487
                        return wolfSSL_connect_TLSv13(ssl);
10488
                #endif
10489
                WOLFSSL_MSG("ProcessReply...");
10490
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
10491
                    WOLFSSL_ERROR(ssl->error);
10492
                    return WOLFSSL_FATAL_ERROR;
10493
                }
10494
                /* if resumption failed, reset needed state */
10495
                else if (neededState == SERVER_FINISHED_COMPLETE) {
10496
                    if (!ssl->options.resuming) {
10497
                    #ifdef WOLFSSL_DTLS
10498
                        if (IsDtlsNotSctpMode(ssl))
10499
                            neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
10500
                        else
10501
                    #endif
10502
                            neededState = SERVER_HELLODONE_COMPLETE;
10503
                    }
10504
                }
10505
                WOLFSSL_MSG("ProcessReply done.");
10506
10507
#ifdef WOLFSSL_DTLS13
10508
                if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)
10509
                    && ssl->dtls13Rtx.sendAcks == 1
10510
                    && ssl->options.seenUnifiedHdr) {
10511
                    /* we aren't negotiated the version yet, so we aren't sure
10512
                     * the other end can speak v1.3. On the other side we have
10513
                     * received a unified records, assuming that the
10514
                     * ServerHello got lost, we will send an empty ACK. In case
10515
                     * the server is a DTLS with version less than 1.3, it
10516
                     * should just ignore the message */
10517
                    ssl->dtls13Rtx.sendAcks = 0;
10518
                    if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
10519
                        if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
10520
                            ssl->dtls13SendingAckOrRtx = 1;
10521
                        WOLFSSL_ERROR(ssl->error);
10522
                        return WOLFSSL_FATAL_ERROR;
10523
                    }
10524
                }
10525
#endif /* WOLFSSL_DTLS13 */
10526
            }
10527
10528
            ssl->options.connectState = HELLO_AGAIN;
10529
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
10530
            FALL_THROUGH;
10531
10532
        case HELLO_AGAIN :
10533
10534
        #ifdef WOLFSSL_TLS13
10535
            if (ssl->options.tls1_3)
10536
                return wolfSSL_connect_TLSv13(ssl);
10537
        #endif
10538
10539
            #ifdef WOLFSSL_DTLS
10540
            if (ssl->options.serverState ==
10541
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
10542
                if (IsDtlsNotSctpMode(ssl)) {
10543
                    /* re-init hashes, exclude first hello and verify request */
10544
                    if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
10545
                        WOLFSSL_ERROR(ssl->error);
10546
                        return WOLFSSL_FATAL_ERROR;
10547
                    }
10548
                    if ( (ssl->error = SendClientHello(ssl)) != 0) {
10549
                        WOLFSSL_ERROR(ssl->error);
10550
                        return WOLFSSL_FATAL_ERROR;
10551
                    }
10552
                }
10553
            }
10554
            #endif
10555
10556
            ssl->options.connectState = HELLO_AGAIN_REPLY;
10557
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
10558
            FALL_THROUGH;
10559
10560
        case HELLO_AGAIN_REPLY :
10561
            #ifdef WOLFSSL_DTLS
10562
                if (IsDtlsNotSctpMode(ssl)) {
10563
                    neededState = ssl->options.resuming ?
10564
                           SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
10565
10566
                    /* get response */
10567
                    while (ssl->options.serverState < neededState) {
10568
                        if ( (ssl->error = ProcessReply(ssl)) < 0) {
10569
                            WOLFSSL_ERROR(ssl->error);
10570
                            return WOLFSSL_FATAL_ERROR;
10571
                        }
10572
                        /* if resumption failed, reset needed state */
10573
                        if (neededState == SERVER_FINISHED_COMPLETE) {
10574
                            if (!ssl->options.resuming)
10575
                                neededState = SERVER_HELLODONE_COMPLETE;
10576
                        }
10577
                    }
10578
                }
10579
            #endif
10580
10581
            ssl->options.connectState = FIRST_REPLY_DONE;
10582
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
10583
            FALL_THROUGH;
10584
10585
        case FIRST_REPLY_DONE :
10586
            if (ssl->options.certOnly)
10587
                return WOLFSSL_SUCCESS;
10588
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
10589
                #ifdef WOLFSSL_TLS13
10590
                    if (ssl->options.tls1_3)
10591
                        return wolfSSL_connect_TLSv13(ssl);
10592
                #endif
10593
                if (ssl->options.sendVerify) {
10594
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
10595
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
10596
                        WOLFSSL_ERROR(ssl->error);
10597
                        return WOLFSSL_FATAL_ERROR;
10598
                    }
10599
                    WOLFSSL_MSG("sent: certificate");
10600
                }
10601
10602
            #endif
10603
            ssl->options.connectState = FIRST_REPLY_FIRST;
10604
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
10605
            FALL_THROUGH;
10606
10607
        case FIRST_REPLY_FIRST :
10608
        #ifdef WOLFSSL_TLS13
10609
            if (ssl->options.tls1_3)
10610
                return wolfSSL_connect_TLSv13(ssl);
10611
        #endif
10612
            if (!ssl->options.resuming) {
10613
                if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
10614
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
10615
#ifdef WOLFSSL_EXTRA_ALERTS
10616
                    if (ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY) ||
10617
                        ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) {
10618
                        SendAlert(ssl, alert_fatal, handshake_failure);
10619
                    }
10620
#endif
10621
                    WOLFSSL_ERROR(ssl->error);
10622
                    return WOLFSSL_FATAL_ERROR;
10623
                }
10624
                WOLFSSL_MSG("sent: client key exchange");
10625
            }
10626
10627
            ssl->options.connectState = FIRST_REPLY_SECOND;
10628
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
10629
            FALL_THROUGH;
10630
10631
    #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
10632
        case FIRST_REPLY_SECOND :
10633
            /* CLIENT: Fail-safe for Server Authentication. */
10634
            if (!ssl->options.peerAuthGood) {
10635
                WOLFSSL_MSG("Server authentication did not happen");
10636
                ssl->error = NO_PEER_VERIFY;
10637
                return WOLFSSL_FATAL_ERROR;
10638
            }
10639
10640
            #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
10641
                if (ssl->options.sendVerify) {
10642
                    if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
10643
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
10644
                        WOLFSSL_ERROR(ssl->error);
10645
                        return WOLFSSL_FATAL_ERROR;
10646
                    }
10647
                    WOLFSSL_MSG("sent: certificate verify");
10648
                }
10649
            #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
10650
            ssl->options.connectState = FIRST_REPLY_THIRD;
10651
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
10652
            FALL_THROUGH;
10653
10654
        case FIRST_REPLY_THIRD :
10655
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
10656
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
10657
                WOLFSSL_ERROR(ssl->error);
10658
                return WOLFSSL_FATAL_ERROR;
10659
            }
10660
            WOLFSSL_MSG("sent: change cipher spec");
10661
            ssl->options.connectState = FIRST_REPLY_FOURTH;
10662
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
10663
            FALL_THROUGH;
10664
10665
        case FIRST_REPLY_FOURTH :
10666
            if ( (ssl->error = SendFinished(ssl)) != 0) {
10667
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
10668
                WOLFSSL_ERROR(ssl->error);
10669
                return WOLFSSL_FATAL_ERROR;
10670
            }
10671
            WOLFSSL_MSG("sent: finished");
10672
            ssl->options.connectState = FINISHED_DONE;
10673
            WOLFSSL_MSG("connect state: FINISHED_DONE");
10674
            FALL_THROUGH;
10675
10676
#ifdef WOLFSSL_DTLS13
10677
        case WAIT_FINISHED_ACK:
10678
            ssl->options.connectState = FINISHED_DONE;
10679
            FALL_THROUGH;
10680
#endif /* WOLFSSL_DTLS13 */
10681
10682
        case FINISHED_DONE :
10683
            /* get response */
10684
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
10685
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
10686
                    WOLFSSL_ERROR(ssl->error);
10687
                    return WOLFSSL_FATAL_ERROR;
10688
                }
10689
10690
            ssl->options.connectState = SECOND_REPLY_DONE;
10691
            WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
10692
            FALL_THROUGH;
10693
10694
        case SECOND_REPLY_DONE:
10695
        #ifndef NO_HANDSHAKE_DONE_CB
10696
            if (ssl->hsDoneCb) {
10697
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
10698
                if (cbret < 0) {
10699
                    ssl->error = cbret;
10700
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
10701
                    return WOLFSSL_FATAL_ERROR;
10702
                }
10703
            }
10704
        #endif /* NO_HANDSHAKE_DONE_CB */
10705
10706
            if (!ssl->options.dtls) {
10707
                if (!ssl->options.keepResources) {
10708
                    FreeHandshakeResources(ssl);
10709
                }
10710
            }
10711
        #ifdef WOLFSSL_DTLS
10712
            else {
10713
                ssl->options.dtlsHsRetain = 1;
10714
            }
10715
        #endif /* WOLFSSL_DTLS */
10716
10717
        #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
10718
            /* This may be necessary in async so that we don't try to
10719
             * renegotiate again */
10720
            if (ssl->secure_renegotiation &&
10721
                    ssl->secure_renegotiation->startScr) {
10722
                ssl->secure_renegotiation->startScr = 0;
10723
            }
10724
        #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
10725
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
10726
            /* Free the remaining async context if not using it for crypto */
10727
            FreeAsyncCtx(ssl, 1);
10728
        #endif
10729
10730
            ssl->error = 0; /* clear the error */
10731
10732
            WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
10733
            return WOLFSSL_SUCCESS;
10734
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
10735
10736
        default:
10737
            WOLFSSL_MSG("Unknown connect state ERROR");
10738
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
10739
        }
10740
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
10741
    }
10742
10743
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
10744
/* end client only parts */
10745
10746
/* server only parts */
10747
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
10748
10749
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
10750
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
10751
    {
10752
        WOLFSSL_STUB("wolfSSLv2_server_method");
10753
        return 0;
10754
    }
10755
    #endif
10756
10757
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
10758
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
10759
    {
10760
        return wolfSSLv3_server_method_ex(NULL);
10761
    }
10762
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
10763
    {
10764
        WOLFSSL_METHOD* method =
10765
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
10766
                                                     heap, DYNAMIC_TYPE_METHOD);
10767
        (void)heap;
10768
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
10769
        if (method) {
10770
            InitSSL_Method(method, MakeSSLv3());
10771
            method->side = WOLFSSL_SERVER_END;
10772
        }
10773
        return method;
10774
    }
10775
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
10776
10777
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
10778
0
    {
10779
0
        return wolfSSLv23_server_method_ex(NULL);
10780
0
    }
10781
10782
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
10783
0
    {
10784
0
        WOLFSSL_METHOD* method =
10785
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
10786
0
                                                     heap, DYNAMIC_TYPE_METHOD);
10787
0
        (void)heap;
10788
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
10789
0
        if (method) {
10790
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
10791
0
        defined(WOLFSSL_SHA512)
10792
0
        #ifdef WOLFSSL_TLS13
10793
0
            InitSSL_Method(method, MakeTLSv1_3());
10794
        #elif !defined(WOLFSSL_NO_TLS12)
10795
            InitSSL_Method(method, MakeTLSv1_2());
10796
        #elif !defined(NO_OLD_TLS)
10797
            InitSSL_Method(method, MakeTLSv1_1());
10798
        #endif
10799
    #else
10800
        #ifndef NO_OLD_TLS
10801
            InitSSL_Method(method, MakeTLSv1_1());
10802
        #else
10803
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
10804
        #endif
10805
    #endif
10806
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
10807
0
            method->downgrade = 1;
10808
0
    #endif
10809
0
            method->side      = WOLFSSL_SERVER_END;
10810
0
        }
10811
0
        return method;
10812
0
    }
10813
10814
10815
    WOLFSSL_ABI
10816
    int wolfSSL_accept(WOLFSSL* ssl)
10817
    {
10818
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
10819
    defined(WOLFSSL_TLS13))
10820
        word16 havePSK = 0;
10821
        word16 haveAnon = 0;
10822
        word16 haveMcast = 0;
10823
#endif
10824
        int ret = 0;
10825
10826
        (void)ret;
10827
10828
        if (ssl == NULL)
10829
            return WOLFSSL_FATAL_ERROR;
10830
10831
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
10832
        if (ssl->options.side == WOLFSSL_NEITHER_END) {
10833
            WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
10834
            ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
10835
            if (ssl->error != WOLFSSL_SUCCESS) {
10836
                WOLFSSL_ERROR(ssl->error);
10837
                return WOLFSSL_FATAL_ERROR;
10838
            }
10839
            ssl->error = 0; /* expected to be zero here */
10840
        }
10841
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
10842
10843
#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)
10844
        return wolfSSL_accept_TLSv13(ssl);
10845
#else
10846
    #ifdef WOLFSSL_TLS13
10847
        if (ssl->options.tls1_3)
10848
            return wolfSSL_accept_TLSv13(ssl);
10849
    #endif
10850
        WOLFSSL_ENTER("wolfSSL_accept");
10851
10852
        /* make sure this wolfSSL object has arrays and rng setup. Protects
10853
         * case where the WOLFSSL object is reused via wolfSSL_clear() */
10854
        if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
10855
            return ret;
10856
        }
10857
10858
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
10859
        if ((ssl->AcceptFilter != NULL) &&
10860
            ((ssl->options.acceptState == ACCEPT_BEGIN)
10861
#ifdef HAVE_SECURE_RENEGOTIATION
10862
             || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
10863
#endif
10864
                ))
10865
        {
10866
            wolfSSL_netfilter_decision_t res;
10867
            if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
10868
                 WOLFSSL_SUCCESS) &&
10869
                (res == WOLFSSL_NETFILTER_REJECT)) {
10870
                ssl->error = SOCKET_FILTERED_E;
10871
                WOLFSSL_ERROR(ssl->error);
10872
                return WOLFSSL_FATAL_ERROR;
10873
            }
10874
        }
10875
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
10876
10877
        #ifdef HAVE_ERRNO_H
10878
            errno = 0;
10879
        #endif
10880
10881
        #ifndef NO_PSK
10882
            havePSK = ssl->options.havePSK;
10883
        #endif
10884
        (void)havePSK;
10885
10886
        #ifdef HAVE_ANON
10887
            haveAnon = ssl->options.useAnon;
10888
        #endif
10889
        (void)haveAnon;
10890
10891
        #ifdef WOLFSSL_MULTICAST
10892
            haveMcast = ssl->options.haveMcast;
10893
        #endif
10894
        (void)haveMcast;
10895
10896
        if (ssl->options.side != WOLFSSL_SERVER_END) {
10897
            ssl->error = SIDE_ERROR;
10898
            WOLFSSL_ERROR(ssl->error);
10899
            return WOLFSSL_FATAL_ERROR;
10900
        }
10901
10902
    #ifndef NO_CERTS
10903
        /* in case used set_accept_state after init */
10904
        if (!havePSK && !haveAnon && !haveMcast) {
10905
        #ifdef WOLFSSL_CERT_SETUP_CB
10906
            if (ssl->ctx->certSetupCb != NULL) {
10907
                WOLFSSL_MSG("CertSetupCb set. server cert and "
10908
                            "key not checked");
10909
            }
10910
            else
10911
        #endif
10912
            {
10913
                if (!ssl->buffers.certificate ||
10914
                    !ssl->buffers.certificate->buffer) {
10915
10916
                    WOLFSSL_MSG("accept error: server cert required");
10917
                    ssl->error = NO_PRIVATE_KEY;
10918
                    WOLFSSL_ERROR(ssl->error);
10919
                    return WOLFSSL_FATAL_ERROR;
10920
                }
10921
10922
                if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
10923
                    /* allow no private key if using existing key */
10924
                #ifdef WOLF_PRIVATE_KEY_ID
10925
                    if (ssl->devId != INVALID_DEVID
10926
                    #ifdef HAVE_PK_CALLBACKS
10927
                        || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
10928
                    #endif
10929
                    ) {
10930
                        WOLFSSL_MSG("Allowing no server private key "
10931
                                    "(external)");
10932
                    }
10933
                    else
10934
                #endif
10935
                    {
10936
                        WOLFSSL_MSG("accept error: server key required");
10937
                        ssl->error = NO_PRIVATE_KEY;
10938
                        WOLFSSL_ERROR(ssl->error);
10939
                        return WOLFSSL_FATAL_ERROR;
10940
                    }
10941
                }
10942
            }
10943
        }
10944
    #endif
10945
10946
    #ifdef WOLFSSL_DTLS
10947
        if (ssl->version.major == DTLS_MAJOR) {
10948
            ssl->options.dtls   = 1;
10949
            ssl->options.tls    = 1;
10950
            ssl->options.tls1_1 = 1;
10951
            if (!IsDtlsNotSctpMode(ssl) || IsSCR(ssl))
10952
                ssl->options.dtlsStateful = 1;
10953
        }
10954
    #endif
10955
10956
        if (ssl->buffers.outputBuffer.length > 0
10957
        #ifdef WOLFSSL_ASYNC_CRYPT
10958
            /* do not send buffered or advance state if last error was an
10959
                async pending operation */
10960
            && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
10961
        #endif
10962
        ) {
10963
            ret = SendBuffered(ssl);
10964
            if (ret == 0) {
10965
                /* fragOffset is non-zero when sending fragments. On the last
10966
                 * fragment, fragOffset is zero again, and the state can be
10967
                 * advanced. */
10968
                if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
10969
                    if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE ||
10970
                        ssl->options.acceptState == SERVER_HELLO_SENT ||
10971
                        ssl->options.acceptState == CERT_SENT ||
10972
                        ssl->options.acceptState == CERT_STATUS_SENT ||
10973
                        ssl->options.acceptState == KEY_EXCHANGE_SENT ||
10974
                        ssl->options.acceptState == CERT_REQ_SENT ||
10975
                        ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE ||
10976
                        ssl->options.acceptState == TICKET_SENT ||
10977
                        ssl->options.acceptState == CHANGE_CIPHER_SENT) {
10978
                        ssl->options.acceptState++;
10979
                        WOLFSSL_MSG("accept state: Advanced from last "
10980
                                    "buffered fragment send");
10981
                    #ifdef WOLFSSL_ASYNC_IO
10982
                        /* Cleanup async */
10983
                        FreeAsyncCtx(ssl, 0);
10984
                    #endif
10985
                    }
10986
                }
10987
                else {
10988
                    WOLFSSL_MSG("accept state: "
10989
                                "Not advanced, more fragments to send");
10990
                }
10991
            }
10992
            else {
10993
                ssl->error = ret;
10994
                WOLFSSL_ERROR(ssl->error);
10995
                return WOLFSSL_FATAL_ERROR;
10996
            }
10997
#ifdef WOLFSSL_DTLS13
10998
            if (ssl->options.dtls)
10999
                ssl->dtls13SendingAckOrRtx = 0;
11000
#endif /* WOLFSSL_DTLS13 */
11001
        }
11002
11003
        ret = RetrySendAlert(ssl);
11004
        if (ret != 0) {
11005
            ssl->error = ret;
11006
            WOLFSSL_ERROR(ssl->error);
11007
            return WOLFSSL_FATAL_ERROR;
11008
        }
11009
11010
        switch (ssl->options.acceptState) {
11011
11012
        case ACCEPT_BEGIN :
11013
#ifdef HAVE_SECURE_RENEGOTIATION
11014
        case ACCEPT_BEGIN_RENEG:
11015
#endif
11016
            /* get response */
11017
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
11018
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
11019
                    WOLFSSL_ERROR(ssl->error);
11020
                    return WOLFSSL_FATAL_ERROR;
11021
                }
11022
#ifdef WOLFSSL_TLS13
11023
            ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
11024
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
11025
            FALL_THROUGH;
11026
11027
        case ACCEPT_CLIENT_HELLO_DONE :
11028
            if (ssl->options.tls1_3) {
11029
                return wolfSSL_accept_TLSv13(ssl);
11030
            }
11031
#endif
11032
11033
            ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
11034
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
11035
            FALL_THROUGH;
11036
11037
        case ACCEPT_FIRST_REPLY_DONE :
11038
            if (ssl->options.returnOnGoodCh) {
11039
                /* Higher level in stack wants us to return. Simulate a
11040
                 * WANT_WRITE to accomplish this. */
11041
                ssl->error = WANT_WRITE;
11042
                return WOLFSSL_FATAL_ERROR;
11043
            }
11044
            if ( (ssl->error = SendServerHello(ssl)) != 0) {
11045
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11046
                WOLFSSL_ERROR(ssl->error);
11047
                return WOLFSSL_FATAL_ERROR;
11048
            }
11049
            ssl->options.acceptState = SERVER_HELLO_SENT;
11050
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
11051
            FALL_THROUGH;
11052
11053
        case SERVER_HELLO_SENT :
11054
        #ifdef WOLFSSL_TLS13
11055
            if (ssl->options.tls1_3) {
11056
                return wolfSSL_accept_TLSv13(ssl);
11057
            }
11058
        #endif
11059
            #ifndef NO_CERTS
11060
                if (!ssl->options.resuming)
11061
                    if ( (ssl->error = SendCertificate(ssl)) != 0) {
11062
                        wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11063
                        WOLFSSL_ERROR(ssl->error);
11064
                        return WOLFSSL_FATAL_ERROR;
11065
                    }
11066
            #endif
11067
            ssl->options.acceptState = CERT_SENT;
11068
            WOLFSSL_MSG("accept state CERT_SENT");
11069
            FALL_THROUGH;
11070
11071
        case CERT_SENT :
11072
            #ifndef NO_CERTS
11073
            if (!ssl->options.resuming)
11074
                if ( (ssl->error = SendCertificateStatus(ssl)) != 0) {
11075
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11076
                    WOLFSSL_ERROR(ssl->error);
11077
                    return WOLFSSL_FATAL_ERROR;
11078
                }
11079
            #endif
11080
            ssl->options.acceptState = CERT_STATUS_SENT;
11081
            WOLFSSL_MSG("accept state CERT_STATUS_SENT");
11082
            FALL_THROUGH;
11083
11084
        case CERT_STATUS_SENT :
11085
        #ifdef WOLFSSL_TLS13
11086
            if (ssl->options.tls1_3) {
11087
                return wolfSSL_accept_TLSv13(ssl);
11088
            }
11089
        #endif
11090
            if (!ssl->options.resuming)
11091
                if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
11092
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11093
                    WOLFSSL_ERROR(ssl->error);
11094
                    return WOLFSSL_FATAL_ERROR;
11095
                }
11096
            ssl->options.acceptState = KEY_EXCHANGE_SENT;
11097
            WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
11098
            FALL_THROUGH;
11099
11100
        case KEY_EXCHANGE_SENT :
11101
            #ifndef NO_CERTS
11102
                if (!ssl->options.resuming) {
11103
                    if (ssl->options.verifyPeer) {
11104
                        if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
11105
                            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11106
                            WOLFSSL_ERROR(ssl->error);
11107
                            return WOLFSSL_FATAL_ERROR;
11108
                        }
11109
                    }
11110
                    else {
11111
                        /* SERVER: Peer auth good if not verifying client. */
11112
                        ssl->options.peerAuthGood = 1;
11113
                    }
11114
                }
11115
            #endif
11116
            ssl->options.acceptState = CERT_REQ_SENT;
11117
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
11118
            FALL_THROUGH;
11119
11120
        case CERT_REQ_SENT :
11121
            if (!ssl->options.resuming)
11122
                if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
11123
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11124
                    WOLFSSL_ERROR(ssl->error);
11125
                    return WOLFSSL_FATAL_ERROR;
11126
                }
11127
            ssl->options.acceptState = SERVER_HELLO_DONE;
11128
            WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
11129
            FALL_THROUGH;
11130
11131
        case SERVER_HELLO_DONE :
11132
            if (!ssl->options.resuming) {
11133
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
11134
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
11135
                        WOLFSSL_ERROR(ssl->error);
11136
                        return WOLFSSL_FATAL_ERROR;
11137
                    }
11138
            }
11139
            ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
11140
            WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
11141
            FALL_THROUGH;
11142
11143
        case ACCEPT_SECOND_REPLY_DONE :
11144
        #ifndef NO_CERTS
11145
            /* SERVER: When not resuming and verifying peer but no certificate
11146
             * received and not failing when not received then peer auth good.
11147
             */
11148
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
11149
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
11150
                ssl->options.peerAuthGood = 1;
11151
            }
11152
        #endif /* !NO_CERTS  */
11153
        #ifdef WOLFSSL_NO_CLIENT_AUTH
11154
            if (!ssl->options.resuming) {
11155
                ssl->options.peerAuthGood = 1;
11156
            }
11157
        #endif
11158
11159
#ifdef HAVE_SESSION_TICKET
11160
            if (ssl->options.createTicket && !ssl->options.noTicketTls12) {
11161
                if ( (ssl->error = SendTicket(ssl)) != 0) {
11162
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11163
                    WOLFSSL_MSG("Thought we need ticket but failed");
11164
                    WOLFSSL_ERROR(ssl->error);
11165
                    return WOLFSSL_FATAL_ERROR;
11166
                }
11167
            }
11168
#endif /* HAVE_SESSION_TICKET */
11169
            ssl->options.acceptState = TICKET_SENT;
11170
            WOLFSSL_MSG("accept state  TICKET_SENT");
11171
            FALL_THROUGH;
11172
11173
        case TICKET_SENT:
11174
            /* SERVER: Fail-safe for CLient Authentication. */
11175
            if (!ssl->options.peerAuthGood) {
11176
                WOLFSSL_MSG("Client authentication did not happen");
11177
                return WOLFSSL_FATAL_ERROR;
11178
            }
11179
11180
            if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
11181
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11182
                WOLFSSL_ERROR(ssl->error);
11183
                return WOLFSSL_FATAL_ERROR;
11184
            }
11185
            ssl->options.acceptState = CHANGE_CIPHER_SENT;
11186
            WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
11187
            FALL_THROUGH;
11188
11189
        case CHANGE_CIPHER_SENT :
11190
            if ( (ssl->error = SendFinished(ssl)) != 0) {
11191
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
11192
                WOLFSSL_ERROR(ssl->error);
11193
                return WOLFSSL_FATAL_ERROR;
11194
            }
11195
11196
            ssl->options.acceptState = ACCEPT_FINISHED_DONE;
11197
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
11198
            FALL_THROUGH;
11199
11200
        case ACCEPT_FINISHED_DONE :
11201
            if (ssl->options.resuming) {
11202
                while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
11203
                    if ( (ssl->error = ProcessReply(ssl)) < 0) {
11204
                        WOLFSSL_ERROR(ssl->error);
11205
                        return WOLFSSL_FATAL_ERROR;
11206
                    }
11207
                }
11208
            }
11209
            ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
11210
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
11211
            FALL_THROUGH;
11212
11213
        case ACCEPT_THIRD_REPLY_DONE :
11214
#ifndef NO_HANDSHAKE_DONE_CB
11215
            if (ssl->hsDoneCb) {
11216
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
11217
                if (cbret < 0) {
11218
                    ssl->error = cbret;
11219
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
11220
                    return WOLFSSL_FATAL_ERROR;
11221
                }
11222
            }
11223
#endif /* NO_HANDSHAKE_DONE_CB */
11224
11225
            if (!ssl->options.dtls) {
11226
                if (!ssl->options.keepResources) {
11227
                    FreeHandshakeResources(ssl);
11228
                }
11229
            }
11230
#ifdef WOLFSSL_DTLS
11231
            else {
11232
                ssl->options.dtlsHsRetain = 1;
11233
            }
11234
#endif /* WOLFSSL_DTLS */
11235
11236
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
11237
            /* This may be necessary in async so that we don't try to
11238
             * renegotiate again */
11239
            if (ssl->secure_renegotiation &&
11240
                    ssl->secure_renegotiation->startScr) {
11241
                ssl->secure_renegotiation->startScr = 0;
11242
            }
11243
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
11244
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
11245
            /* Free the remaining async context if not using it for crypto */
11246
            FreeAsyncCtx(ssl, 1);
11247
#endif
11248
11249
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
11250
            if (ssl->dtls_export) {
11251
                if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
11252
                    WOLFSSL_MSG("Export DTLS session error");
11253
                    WOLFSSL_ERROR(ssl->error);
11254
                    return WOLFSSL_FATAL_ERROR;
11255
                }
11256
            }
11257
#endif
11258
            ssl->error = 0; /* clear the error */
11259
11260
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
11261
            return WOLFSSL_SUCCESS;
11262
11263
        default:
11264
            WOLFSSL_MSG("Unknown accept state ERROR");
11265
            return WOLFSSL_FATAL_ERROR;
11266
        }
11267
#endif /* !WOLFSSL_NO_TLS12 */
11268
    }
11269
11270
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
11271
/* end server only parts */
11272
11273
11274
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
11275
struct chGoodDisableReadCbCtx {
11276
    ClientHelloGoodCb userCb;
11277
    void*             userCtx;
11278
};
11279
11280
static int chGoodDisableReadCB(WOLFSSL* ssl, void* ctx)
11281
{
11282
    struct chGoodDisableReadCbCtx* cb = (struct chGoodDisableReadCbCtx*)ctx;
11283
    int ret = 0;
11284
    if (cb->userCb != NULL)
11285
        ret = cb->userCb(ssl, cb->userCtx);
11286
    if (ret >= 0)
11287
        wolfSSL_SSLDisableRead(ssl);
11288
    return ret;
11289
}
11290
11291
/**
11292
 * Statelessly listen for a connection
11293
 * @param ssl The ssl object to use for listening to connections
11294
 * @return WOLFSSL_SUCCESS - ClientHello containing a valid cookie was received
11295
 *                           The connection can be continued with wolfSSL_accept
11296
 *         WOLFSSL_FAILURE - The I/O layer returned WANT_READ. This is either
11297
 *                           because there is no data to read and we are using
11298
 *                           non-blocking sockets or we sent a cookie request
11299
 *                           and we are waiting for a reply. The user should
11300
 *                           call wolfDTLS_accept_stateless again after data
11301
 *                           becomes available in the I/O layer.
11302
 *         WOLFSSL_FATAL_ERROR - A fatal error occurred. The ssl object should
11303
 *                           be free'd and allocated again to continue.
11304
 */
11305
int wolfDTLS_accept_stateless(WOLFSSL* ssl)
11306
{
11307
    byte disableRead;
11308
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
11309
    struct chGoodDisableReadCbCtx cb;
11310
11311
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
11312
11313
    if (ssl == NULL)
11314
        return WOLFSSL_FATAL_ERROR;
11315
11316
    /* Save this to restore it later */
11317
    disableRead = (byte)ssl->options.disableRead;
11318
    cb.userCb = ssl->chGoodCb;
11319
    cb.userCtx = ssl->chGoodCtx;
11320
11321
    /* Register our own callback so that we can disable reading */
11322
    if (wolfDTLS_SetChGoodCb(ssl, chGoodDisableReadCB, &cb) != WOLFSSL_SUCCESS)
11323
        return WOLFSSL_FATAL_ERROR;
11324
11325
    ssl->options.returnOnGoodCh = 1;
11326
    ret = wolfSSL_accept(ssl);
11327
    ssl->options.returnOnGoodCh = 0;
11328
    /* restore user options */
11329
    ssl->options.disableRead = disableRead;
11330
    (void)wolfDTLS_SetChGoodCb(ssl, cb.userCb, cb.userCtx);
11331
    if (ret == WOLFSSL_SUCCESS) {
11332
        WOLFSSL_MSG("should not happen. maybe the user called "
11333
                    "wolfDTLS_accept_stateless instead of wolfSSL_accept");
11334
    }
11335
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_READ) ||
11336
             ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
11337
        ssl->error = 0;
11338
        if (ssl->options.dtlsStateful)
11339
            ret = WOLFSSL_SUCCESS;
11340
        else
11341
            ret = WOLFSSL_FAILURE;
11342
    }
11343
    else {
11344
        ret = WOLFSSL_FATAL_ERROR;
11345
    }
11346
    return ret;
11347
}
11348
11349
int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx)
11350
{
11351
    WOLFSSL_ENTER("wolfDTLS_SetChGoodCb");
11352
11353
    if (ssl == NULL)
11354
        return BAD_FUNC_ARG;
11355
11356
    ssl->chGoodCb  = cb;
11357
    ssl->chGoodCtx = user_ctx;
11358
11359
    return WOLFSSL_SUCCESS;
11360
}
11361
#endif
11362
11363
#ifndef NO_HANDSHAKE_DONE_CB
11364
11365
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
11366
0
{
11367
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
11368
11369
0
    if (ssl == NULL)
11370
0
        return BAD_FUNC_ARG;
11371
11372
0
    ssl->hsDoneCb  = cb;
11373
0
    ssl->hsDoneCtx = user_ctx;
11374
11375
0
    return WOLFSSL_SUCCESS;
11376
0
}
11377
11378
#endif /* NO_HANDSHAKE_DONE_CB */
11379
11380
WOLFSSL_ABI
11381
int wolfSSL_Cleanup(void)
11382
21.1k
{
11383
21.1k
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
11384
21.1k
    int release = 0;
11385
21.1k
#if !defined(NO_SESSION_CACHE)
11386
21.1k
    int i;
11387
21.1k
    int j;
11388
21.1k
#endif
11389
11390
21.1k
    WOLFSSL_ENTER("wolfSSL_Cleanup");
11391
11392
#ifndef WOLFSSL_MUTEX_INITIALIZER
11393
    if (inits_count_mutex_valid == 1) {
11394
#endif
11395
21.1k
        if (wc_LockMutex(&inits_count_mutex) != 0) {
11396
0
            WOLFSSL_MSG("Bad Lock Mutex count");
11397
0
            return BAD_MUTEX_E;
11398
0
        }
11399
#ifndef WOLFSSL_MUTEX_INITIALIZER
11400
    }
11401
#endif
11402
11403
21.1k
    if (initRefCount > 0) {
11404
4.86k
        --initRefCount;
11405
4.86k
        if (initRefCount == 0)
11406
4.86k
            release = 1;
11407
4.86k
    }
11408
11409
#ifndef WOLFSSL_MUTEX_INITIALIZER
11410
    if (inits_count_mutex_valid == 1) {
11411
#endif
11412
21.1k
        wc_UnLockMutex(&inits_count_mutex);
11413
#ifndef WOLFSSL_MUTEX_INITIALIZER
11414
    }
11415
#endif
11416
11417
21.1k
    if (!release)
11418
16.2k
        return ret;
11419
11420
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
11421
    wolfSSL_crypto_policy_disable();
11422
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
11423
11424
#ifdef OPENSSL_EXTRA
11425
    wolfSSL_BN_free_one();
11426
#endif
11427
11428
4.86k
#ifndef NO_SESSION_CACHE
11429
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
11430
    for (i = 0; i < SESSION_ROWS; ++i) {
11431
        if ((SessionCache[i].lock_valid == 1) &&
11432
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
11433
            if (ret == WOLFSSL_SUCCESS)
11434
                ret = BAD_MUTEX_E;
11435
        }
11436
        SessionCache[i].lock_valid = 0;
11437
    }
11438
    #else
11439
4.86k
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
11440
0
        if (ret == WOLFSSL_SUCCESS)
11441
0
            ret = BAD_MUTEX_E;
11442
0
    }
11443
4.86k
    session_lock_valid = 0;
11444
4.86k
    #endif
11445
58.4k
    for (i = 0; i < SESSION_ROWS; i++) {
11446
214k
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
11447
    #ifdef SESSION_CACHE_DYNAMIC_MEM
11448
            if (SessionCache[i].Sessions[j]) {
11449
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
11450
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
11451
                      DYNAMIC_TYPE_SESSION);
11452
                SessionCache[i].Sessions[j] = NULL;
11453
            }
11454
    #else
11455
160k
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
11456
160k
    #endif
11457
160k
        }
11458
53.5k
    }
11459
4.86k
    #ifndef NO_CLIENT_CACHE
11460
    #ifndef WOLFSSL_MUTEX_INITIALIZER
11461
    if ((clisession_mutex_valid == 1) &&
11462
        (wc_FreeMutex(&clisession_mutex) != 0)) {
11463
        if (ret == WOLFSSL_SUCCESS)
11464
            ret = BAD_MUTEX_E;
11465
    }
11466
    clisession_mutex_valid = 0;
11467
    #endif
11468
4.86k
    #endif
11469
4.86k
#endif /* !NO_SESSION_CACHE */
11470
11471
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
11472
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
11473
    if ((inits_count_mutex_valid == 1) &&
11474
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
11475
        if (ret == WOLFSSL_SUCCESS)
11476
            ret = BAD_MUTEX_E;
11477
    }
11478
    inits_count_mutex_valid = 0;
11479
#endif
11480
11481
#ifdef OPENSSL_EXTRA
11482
    wolfSSL_RAND_Cleanup();
11483
#endif
11484
11485
4.86k
    if (wolfCrypt_Cleanup() != 0) {
11486
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
11487
0
        if (ret == WOLFSSL_SUCCESS)
11488
0
            ret = WC_CLEANUP_E;
11489
0
    }
11490
11491
#if FIPS_VERSION_GE(5,1)
11492
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
11493
        if (ret == WOLFSSL_SUCCESS)
11494
            ret = WC_CLEANUP_E;
11495
    }
11496
#endif
11497
11498
4.86k
#ifdef HAVE_GLOBAL_RNG
11499
#ifndef WOLFSSL_MUTEX_INITIALIZER
11500
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
11501
        if (ret == WOLFSSL_SUCCESS)
11502
            ret = BAD_MUTEX_E;
11503
    }
11504
    globalRNGMutex_valid = 0;
11505
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
11506
11507
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
11508
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
11509
    gDrbgDefCtx = NULL;
11510
    #endif
11511
4.86k
#endif
11512
11513
#ifdef HAVE_EX_DATA_CRYPTO
11514
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
11515
    crypto_ex_cb_ctx_session = NULL;
11516
#endif
11517
11518
#ifdef WOLFSSL_MEM_FAIL_COUNT
11519
    wc_MemFailCount_Free();
11520
#endif
11521
11522
4.86k
    return ret;
11523
21.1k
}
11524
11525
11526
/* call before SSL_connect, if verifying will add name check to
11527
   date check and signature check */
11528
WOLFSSL_ABI
11529
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
11530
0
{
11531
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
11532
11533
0
    if (ssl == NULL || dn == NULL) {
11534
0
        WOLFSSL_MSG("Bad function argument: NULL");
11535
0
        return WOLFSSL_FAILURE;
11536
0
    }
11537
11538
0
    if (ssl->buffers.domainName.buffer)
11539
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
11540
11541
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
11542
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
11543
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
11544
11545
0
    if (ssl->buffers.domainName.buffer) {
11546
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
11547
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
11548
0
        domainName[ssl->buffers.domainName.length] = '\0';
11549
0
        return WOLFSSL_SUCCESS;
11550
0
    }
11551
0
    else {
11552
0
        ssl->error = MEMORY_ERROR;
11553
0
        return WOLFSSL_FAILURE;
11554
0
    }
11555
0
}
11556
11557
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
11558
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
11559
    if (ssl == NULL) {
11560
        return NULL;
11561
    }
11562
11563
    if (ssl->buffers.domainName.buffer)
11564
        return (const char *)ssl->buffers.domainName.buffer;
11565
    else if (ssl->session && ssl->session->peer)
11566
        return ssl->session->peer->subjectCN;
11567
#ifdef KEEP_PEER_CERT
11568
    else if (ssl->peerCert.subjectCN[0])
11569
        return ssl->peerCert.subjectCN;
11570
#endif
11571
    else {
11572
        ssl->error = NO_PEER_CERT;
11573
        return NULL;
11574
    }
11575
}
11576
11577
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
11578
11579
/* turn on wolfSSL zlib compression
11580
   returns WOLFSSL_SUCCESS for success, else error (not built in)
11581
*/
11582
int wolfSSL_set_compression(WOLFSSL* ssl)
11583
0
{
11584
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
11585
0
    (void)ssl;
11586
#ifdef HAVE_LIBZ
11587
    ssl->options.usingCompression = 1;
11588
    return WOLFSSL_SUCCESS;
11589
#else
11590
0
    return NOT_COMPILED_IN;
11591
0
#endif
11592
0
}
11593
11594
11595
#ifndef USE_WINDOWS_API
11596
    #if !defined(NO_WRITEV) && !defined(NO_TLS)
11597
11598
        /* simulate writev semantics, doesn't actually do block at a time though
11599
           because of SSL_write behavior and because front adds may be small */
11600
        int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt)
11601
0
        {
11602
0
        #ifdef WOLFSSL_SMALL_STACK
11603
0
            byte   staticBuffer[1]; /* force heap usage */
11604
        #else
11605
            byte   staticBuffer[FILE_BUFFER_SIZE];
11606
        #endif
11607
0
            byte* myBuffer  = staticBuffer;
11608
0
            int   dynamic   = 0;
11609
0
            size_t sending   = 0;
11610
0
            size_t idx       = 0;
11611
0
            int   i;
11612
0
            int   ret;
11613
11614
0
            WOLFSSL_ENTER("wolfSSL_writev");
11615
11616
0
            for (i = 0; i < iovcnt; i++)
11617
0
                if (! WC_SAFE_SUM_UNSIGNED(size_t, sending, iov[i].iov_len,
11618
0
                                           sending))
11619
0
                    return BUFFER_E;
11620
11621
0
            if (sending > sizeof(staticBuffer)) {
11622
0
                myBuffer = (byte*)XMALLOC(sending, ssl->heap,
11623
0
                                          DYNAMIC_TYPE_WRITEV);
11624
0
                if (!myBuffer)
11625
0
                    return MEMORY_ERROR;
11626
11627
0
                dynamic = 1;
11628
0
            }
11629
11630
0
            for (i = 0; i < iovcnt; i++) {
11631
0
                XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
11632
0
                idx += (int)iov[i].iov_len;
11633
0
            }
11634
11635
           /* myBuffer may not be initialized fully, but the span up to the
11636
            * sending length will be.
11637
            */
11638
0
            PRAGMA_GCC_DIAG_PUSH
11639
0
            PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
11640
0
            ret = wolfSSL_write_internal(ssl, myBuffer, sending);
11641
0
            PRAGMA_GCC_DIAG_POP
11642
11643
0
            if (dynamic)
11644
0
                XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
11645
11646
0
            return ret;
11647
0
        }
11648
    #endif
11649
#endif
11650
11651
11652
#ifdef WOLFSSL_CALLBACKS
11653
11654
    typedef struct itimerval Itimerval;
11655
11656
    /* don't keep calling simple functions while setting up timer and signals
11657
       if no inlining these are the next best */
11658
11659
    #define AddTimes(a, b, c)                       \
11660
        do {                                        \
11661
            (c).tv_sec  = (a).tv_sec + (b).tv_sec;  \
11662
            (c).tv_usec = (a).tv_usec + (b).tv_usec;\
11663
            if ((c).tv_usec >=  1000000) {          \
11664
                (c).tv_sec++;                       \
11665
                (c).tv_usec -= 1000000;             \
11666
            }                                       \
11667
        } while (0)
11668
11669
11670
    #define SubtractTimes(a, b, c)                  \
11671
        do {                                        \
11672
            (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
11673
            (c).tv_usec = (a).tv_usec - (b).tv_usec;\
11674
            if ((c).tv_usec < 0) {                  \
11675
                (c).tv_sec--;                       \
11676
                (c).tv_usec += 1000000;             \
11677
            }                                       \
11678
        } while (0)
11679
11680
    #define CmpTimes(a, b, cmp)                     \
11681
        (((a).tv_sec  ==  (b).tv_sec) ?             \
11682
            ((a).tv_usec cmp (b).tv_usec) :         \
11683
            ((a).tv_sec  cmp (b).tv_sec))           \
11684
11685
11686
    /* do nothing handler */
11687
    static void myHandler(int signo)
11688
    {
11689
        (void)signo;
11690
        return;
11691
    }
11692
11693
11694
    static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
11695
                                 TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
11696
    {
11697
        int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
11698
        int       oldTimerOn = 0;   /* was timer already on */
11699
        WOLFSSL_TIMEVAL startTime;
11700
        WOLFSSL_TIMEVAL endTime;
11701
        WOLFSSL_TIMEVAL totalTime;
11702
        Itimerval myTimeout;
11703
        Itimerval oldTimeout; /* if old timer adjust from total time to reset */
11704
        struct sigaction act, oact;
11705
11706
        #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; }
11707
11708
        if (hsCb) {
11709
            ssl->hsInfoOn = 1;
11710
            InitHandShakeInfo(&ssl->handShakeInfo, ssl);
11711
        }
11712
        if (toCb) {
11713
            ssl->toInfoOn = 1;
11714
            InitTimeoutInfo(&ssl->timeoutInfo);
11715
11716
            if (gettimeofday(&startTime, 0) < 0)
11717
                ERR_OUT(GETTIME_ERROR);
11718
11719
            /* use setitimer to simulate getitimer, init 0 myTimeout */
11720
            myTimeout.it_interval.tv_sec  = 0;
11721
            myTimeout.it_interval.tv_usec = 0;
11722
            myTimeout.it_value.tv_sec     = 0;
11723
            myTimeout.it_value.tv_usec    = 0;
11724
            if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0)
11725
                ERR_OUT(SETITIMER_ERROR);
11726
11727
            if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) {
11728
                oldTimerOn = 1;
11729
11730
                /* is old timer going to expire before ours */
11731
                if (CmpTimes(oldTimeout.it_value, timeout, <)) {
11732
                    timeout.tv_sec  = oldTimeout.it_value.tv_sec;
11733
                    timeout.tv_usec = oldTimeout.it_value.tv_usec;
11734
                }
11735
            }
11736
            myTimeout.it_value.tv_sec  = timeout.tv_sec;
11737
            myTimeout.it_value.tv_usec = timeout.tv_usec;
11738
11739
            /* set up signal handler, don't restart socket send/recv */
11740
            act.sa_handler = myHandler;
11741
            sigemptyset(&act.sa_mask);
11742
            act.sa_flags = 0;
11743
#ifdef SA_INTERRUPT
11744
            act.sa_flags |= SA_INTERRUPT;
11745
#endif
11746
            if (sigaction(SIGALRM, &act, &oact) < 0)
11747
                ERR_OUT(SIGACT_ERROR);
11748
11749
            if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0)
11750
                ERR_OUT(SETITIMER_ERROR);
11751
        }
11752
11753
        /* do main work */
11754
#ifndef NO_WOLFSSL_CLIENT
11755
        if (ssl->options.side == WOLFSSL_CLIENT_END)
11756
            ret = wolfSSL_connect(ssl);
11757
#endif
11758
#ifndef NO_WOLFSSL_SERVER
11759
        if (ssl->options.side == WOLFSSL_SERVER_END)
11760
            ret = wolfSSL_accept(ssl);
11761
#endif
11762
11763
        /* do callbacks */
11764
        if (toCb) {
11765
            if (oldTimerOn) {
11766
                if (gettimeofday(&endTime, 0) < 0)
11767
                    ERR_OUT(SYSLIB_FAILED_E);
11768
                SubtractTimes(endTime, startTime, totalTime);
11769
                /* adjust old timer for elapsed time */
11770
                if (CmpTimes(totalTime, oldTimeout.it_value, <))
11771
                    SubtractTimes(oldTimeout.it_value, totalTime,
11772
                                  oldTimeout.it_value);
11773
                else {
11774
                    /* reset value to interval, may be off */
11775
                    oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec;
11776
                    oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec;
11777
                }
11778
                /* keep iter the same whether there or not */
11779
            }
11780
            /* restore old handler */
11781
            if (sigaction(SIGALRM, &oact, 0) < 0)
11782
                ret = SIGACT_ERROR;    /* more pressing error, stomp */
11783
            else
11784
                /* use old settings which may turn off (expired or not there) */
11785
                if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0)
11786
                    ret = SETITIMER_ERROR;
11787
11788
            /* if we had a timeout call callback */
11789
            if (ssl->timeoutInfo.timeoutName[0]) {
11790
                ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
11791
                ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
11792
                (toCb)(&ssl->timeoutInfo);
11793
            }
11794
            ssl->toInfoOn = 0;
11795
        }
11796
11797
        /* clean up buffers allocated by AddPacketInfo */
11798
        FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
11799
11800
        if (hsCb) {
11801
            FinishHandShakeInfo(&ssl->handShakeInfo);
11802
            (hsCb)(&ssl->handShakeInfo);
11803
            ssl->hsInfoOn = 0;
11804
        }
11805
        return ret;
11806
    }
11807
11808
11809
#ifndef NO_WOLFSSL_CLIENT
11810
11811
    int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
11812
                          TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
11813
    {
11814
        WOLFSSL_ENTER("wolfSSL_connect_ex");
11815
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
11816
    }
11817
11818
#endif
11819
11820
11821
#ifndef NO_WOLFSSL_SERVER
11822
11823
    int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
11824
                         TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
11825
    {
11826
        WOLFSSL_ENTER("wolfSSL_accept_ex");
11827
        return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
11828
    }
11829
11830
#endif
11831
11832
#endif /* WOLFSSL_CALLBACKS */
11833
11834
11835
#ifndef NO_PSK
11836
11837
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
11838
                                         wc_psk_client_callback cb)
11839
    {
11840
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
11841
11842
        if (ctx == NULL)
11843
            return;
11844
11845
        ctx->havePSK = 1;
11846
        ctx->client_psk_cb = cb;
11847
    }
11848
11849
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
11850
    {
11851
        byte haveRSA = 1;
11852
        int  keySz   = 0;
11853
11854
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
11855
11856
        if (ssl == NULL)
11857
            return;
11858
11859
        ssl->options.havePSK = 1;
11860
        ssl->options.client_psk_cb = cb;
11861
11862
        #ifdef NO_RSA
11863
            haveRSA = 0;
11864
        #endif
11865
        #ifndef NO_CERTS
11866
            keySz = ssl->buffers.keySz;
11867
        #endif
11868
        if (AllocateSuites(ssl) != 0)
11869
            return;
11870
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
11871
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
11872
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
11873
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
11874
    }
11875
    #ifdef OPENSSL_EXTRA
11876
    /**
11877
     * set call back function for psk session use
11878
     * @param ssl  a pointer to WOLFSSL structure
11879
     * @param cb   a function pointer to wc_psk_use_session_cb
11880
     * @return none
11881
     */
11882
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
11883
                                                wc_psk_use_session_cb_func cb)
11884
    {
11885
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
11886
11887
        if (ssl != NULL) {
11888
            ssl->options.havePSK = 1;
11889
            ssl->options.session_psk_cb = cb;
11890
        }
11891
11892
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
11893
    }
11894
    #endif
11895
11896
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
11897
                                         wc_psk_server_callback cb)
11898
    {
11899
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
11900
        if (ctx == NULL)
11901
            return;
11902
        ctx->havePSK = 1;
11903
        ctx->server_psk_cb = cb;
11904
    }
11905
11906
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
11907
    {
11908
        byte haveRSA = 1;
11909
        int  keySz   = 0;
11910
11911
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
11912
        if (ssl == NULL)
11913
            return;
11914
11915
        ssl->options.havePSK = 1;
11916
        ssl->options.server_psk_cb = cb;
11917
11918
        #ifdef NO_RSA
11919
            haveRSA = 0;
11920
        #endif
11921
        #ifndef NO_CERTS
11922
            keySz = ssl->buffers.keySz;
11923
        #endif
11924
        if (AllocateSuites(ssl) != 0)
11925
            return;
11926
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
11927
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
11928
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
11929
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
11930
    }
11931
11932
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
11933
    {
11934
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
11935
11936
        if (ssl == NULL || ssl->arrays == NULL)
11937
            return NULL;
11938
11939
        return ssl->arrays->server_hint;
11940
    }
11941
11942
11943
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
11944
    {
11945
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
11946
11947
        if (ssl == NULL || ssl->arrays == NULL)
11948
            return NULL;
11949
11950
        return ssl->arrays->client_identity;
11951
    }
11952
11953
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
11954
    {
11955
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
11956
        if (hint == 0)
11957
            ctx->server_hint[0] = '\0';
11958
        else {
11959
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
11960
            #ifdef WOLFSSL_QT
11961
            ctx->havePSK=1;
11962
            #endif
11963
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
11964
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
11965
        }
11966
        return WOLFSSL_SUCCESS;
11967
    }
11968
11969
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
11970
    {
11971
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
11972
11973
        if (ssl == NULL || ssl->arrays == NULL)
11974
            return WOLFSSL_FAILURE;
11975
11976
        if (hint == 0)
11977
            ssl->arrays->server_hint[0] = 0;
11978
        else {
11979
            XSTRNCPY(ssl->arrays->server_hint, hint,
11980
                                            sizeof(ssl->arrays->server_hint)-1);
11981
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
11982
        }
11983
        return WOLFSSL_SUCCESS;
11984
    }
11985
11986
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
11987
    {
11988
        return ssl ? ssl->options.psk_ctx : NULL;
11989
    }
11990
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
11991
    {
11992
        return ctx ? ctx->psk_ctx : NULL;
11993
    }
11994
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
11995
    {
11996
        if (ssl == NULL)
11997
            return WOLFSSL_FAILURE;
11998
        ssl->options.psk_ctx = psk_ctx;
11999
        return WOLFSSL_SUCCESS;
12000
    }
12001
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
12002
    {
12003
        if (ctx == NULL)
12004
            return WOLFSSL_FAILURE;
12005
        ctx->psk_ctx = psk_ctx;
12006
        return WOLFSSL_SUCCESS;
12007
    }
12008
#endif /* NO_PSK */
12009
12010
12011
#ifdef HAVE_ANON
12012
12013
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
12014
    {
12015
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
12016
12017
        if (ctx == NULL)
12018
            return WOLFSSL_FAILURE;
12019
12020
        ctx->useAnon = 1;
12021
12022
        return WOLFSSL_SUCCESS;
12023
    }
12024
12025
#endif /* HAVE_ANON */
12026
12027
#ifndef NO_CERTS
12028
12029
    /* unload any certs or keys that SSL owns, leave CTX as is
12030
       WOLFSSL_SUCCESS on ok */
12031
    int wolfSSL_UnloadCertsKeys(WOLFSSL* ssl)
12032
79.0k
    {
12033
79.0k
        if (ssl == NULL) {
12034
0
            WOLFSSL_MSG("Null function arg");
12035
0
            return BAD_FUNC_ARG;
12036
0
        }
12037
12038
79.0k
        if (ssl->buffers.weOwnCert && !ssl->keepCert) {
12039
62.6k
            WOLFSSL_MSG("Unloading cert");
12040
62.6k
            FreeDer(&ssl->buffers.certificate);
12041
            #ifdef KEEP_OUR_CERT
12042
            wolfSSL_X509_free(ssl->ourCert);
12043
            ssl->ourCert = NULL;
12044
            #endif
12045
62.6k
            ssl->buffers.weOwnCert = 0;
12046
62.6k
        }
12047
12048
79.0k
        if (ssl->buffers.weOwnCertChain) {
12049
0
            WOLFSSL_MSG("Unloading cert chain");
12050
0
            FreeDer(&ssl->buffers.certChain);
12051
0
            ssl->buffers.weOwnCertChain = 0;
12052
0
        }
12053
12054
79.0k
        if (ssl->buffers.weOwnKey) {
12055
62.6k
            WOLFSSL_MSG("Unloading key");
12056
62.6k
            ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length);
12057
62.6k
            FreeDer(&ssl->buffers.key);
12058
        #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12059
            FreeDer(&ssl->buffers.keyMask);
12060
        #endif
12061
62.6k
            ssl->buffers.weOwnKey = 0;
12062
62.6k
        }
12063
12064
#ifdef WOLFSSL_DUAL_ALG_CERTS
12065
        if (ssl->buffers.weOwnAltKey) {
12066
            WOLFSSL_MSG("Unloading alt key");
12067
            ForceZero(ssl->buffers.altKey->buffer, ssl->buffers.altKey->length);
12068
            FreeDer(&ssl->buffers.altKey);
12069
        #ifdef WOLFSSL_BLIND_PRIVATE_KEY
12070
            FreeDer(&ssl->buffers.altKeyMask);
12071
        #endif
12072
            ssl->buffers.weOwnAltKey = 0;
12073
        }
12074
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12075
12076
79.0k
        return WOLFSSL_SUCCESS;
12077
79.0k
    }
12078
12079
12080
    int wolfSSL_CTX_UnloadCAs(WOLFSSL_CTX* ctx)
12081
0
    {
12082
0
        WOLFSSL_ENTER("wolfSSL_CTX_UnloadCAs");
12083
12084
0
        if (ctx == NULL)
12085
0
            return BAD_FUNC_ARG;
12086
12087
0
        return wolfSSL_CertManagerUnloadCAs(ctx->cm);
12088
0
    }
12089
12090
    int wolfSSL_CTX_UnloadIntermediateCerts(WOLFSSL_CTX* ctx)
12091
0
    {
12092
0
        int ret;
12093
12094
0
        WOLFSSL_ENTER("wolfSSL_CTX_UnloadIntermediateCerts");
12095
12096
0
        if (ctx == NULL)
12097
0
            return BAD_FUNC_ARG;
12098
12099
0
        ret = wolfSSL_RefWithMutexLock(&ctx->ref);
12100
0
        if (ret < 0)
12101
0
            return ret;
12102
12103
0
        if (ctx->ref.count > 1) {
12104
0
            WOLFSSL_MSG("ctx object must have a ref count of 1 before "
12105
0
                        "unloading intermediate certs");
12106
0
            ret = BAD_STATE_E;
12107
0
        }
12108
0
        else {
12109
0
            ret = wolfSSL_CertManagerUnloadIntermediateCerts(ctx->cm);
12110
0
        }
12111
12112
0
        if (wolfSSL_RefWithMutexUnlock(&ctx->ref) != 0)
12113
0
            WOLFSSL_MSG("Failed to unlock mutex!");
12114
12115
0
        return ret;
12116
0
    }
12117
12118
12119
#ifdef WOLFSSL_TRUST_PEER_CERT
12120
    int wolfSSL_CTX_Unload_trust_peers(WOLFSSL_CTX* ctx)
12121
    {
12122
        WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers");
12123
12124
        if (ctx == NULL)
12125
            return BAD_FUNC_ARG;
12126
12127
        return wolfSSL_CertManagerUnload_trust_peers(ctx->cm);
12128
    }
12129
12130
#ifdef WOLFSSL_LOCAL_X509_STORE
12131
    int wolfSSL_Unload_trust_peers(WOLFSSL* ssl)
12132
    {
12133
        WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers");
12134
12135
        if (ssl == NULL)
12136
            return BAD_FUNC_ARG;
12137
12138
        SSL_CM_WARNING(ssl);
12139
        return wolfSSL_CertManagerUnload_trust_peers(SSL_CM(ssl));
12140
    }
12141
#endif /* WOLFSSL_LOCAL_X509_STORE */
12142
#endif /* WOLFSSL_TRUST_PEER_CERT */
12143
/* old NO_FILESYSTEM end */
12144
#endif /* !NO_CERTS */
12145
12146
12147
#ifdef OPENSSL_EXTRA
12148
12149
    int wolfSSL_add_all_algorithms(void)
12150
    {
12151
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
12152
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
12153
            return WOLFSSL_SUCCESS;
12154
        else
12155
            return WOLFSSL_FATAL_ERROR;
12156
    }
12157
12158
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
12159
    {
12160
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
12161
12162
        if  (wolfSSL_add_all_algorithms() ==
12163
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
12164
        {
12165
            return WOLFSSL_FATAL_ERROR;
12166
        }
12167
12168
        return  WOLFSSL_SUCCESS;
12169
    }
12170
12171
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
12172
    {
12173
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
12174
        /* This function is currently the same as
12175
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
12176
        the use of a wolfssl.cnf type configuration file and is only used for
12177
        OpenSSL compatibility. */
12178
12179
        if (wolfSSL_add_all_algorithms() ==
12180
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
12181
        {
12182
            return WOLFSSL_FATAL_ERROR;
12183
        }
12184
        return WOLFSSL_SUCCESS;
12185
    }
12186
12187
#endif
12188
12189
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
12190
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
12191
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
12192
    {
12193
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
12194
        if (mode)
12195
            ctx->quietShutdown = 1;
12196
    }
12197
12198
12199
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
12200
    {
12201
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
12202
        if (mode)
12203
            ssl->options.quietShutdown = 1;
12204
    }
12205
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
12206
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
12207
12208
#ifdef OPENSSL_EXTRA
12209
#ifndef NO_BIO
12210
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
12211
    {
12212
        WOLFSSL_ENTER("wolfSSL_set_bio");
12213
12214
        if (ssl == NULL) {
12215
            WOLFSSL_MSG("Bad argument, ssl was NULL");
12216
            return;
12217
        }
12218
12219
        /* free any existing WOLFSSL_BIOs in use but don't free those in
12220
         * a chain */
12221
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
12222
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
12223
                if (ssl->biowr != NULL && ssl->biowr->prev != NULL)
12224
                    wolfSSL_BIO_free(ssl->biowr);
12225
                ssl->biowr = NULL;
12226
            }
12227
            if (ssl->biord->prev != NULL)
12228
                wolfSSL_BIO_free(ssl->biord);
12229
            ssl->biord = NULL;
12230
        }
12231
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
12232
            if (ssl->biowr->prev != NULL)
12233
                wolfSSL_BIO_free(ssl->biowr);
12234
            ssl->biowr = NULL;
12235
        }
12236
12237
        /* set flag obviously */
12238
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
12239
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
12240
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
12241
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
12242
12243
        if (flags & WOLFSSL_BIO_FLAG_READ)
12244
            ssl->biord = rd;
12245
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
12246
            ssl->biowr = wr;
12247
12248
        /* set SSL to use BIO callbacks instead */
12249
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
12250
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
12251
        {
12252
            ssl->CBIORecv = SslBioReceive;
12253
        }
12254
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
12255
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
12256
        {
12257
            ssl->CBIOSend = SslBioSend;
12258
        }
12259
12260
        /* User programs should always retry reading from these BIOs */
12261
        if (rd) {
12262
            /* User writes to rd */
12263
            wolfSSL_BIO_set_retry_write(rd);
12264
        }
12265
        if (wr) {
12266
            /* User reads from wr */
12267
            wolfSSL_BIO_set_retry_read(wr);
12268
        }
12269
    }
12270
12271
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
12272
    {
12273
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
12274
    }
12275
12276
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
12277
    {
12278
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
12279
    }
12280
12281
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
12282
    {
12283
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
12284
    }
12285
12286
#endif /* !NO_BIO */
12287
#endif /* OPENSSL_EXTRA */
12288
12289
#ifndef WOLFSSL_NO_CA_NAMES
12290
    void wolfSSL_CTX_set_client_CA_list(WOLFSSL_CTX* ctx,
12291
                                       WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
12292
    {
12293
        WOLFSSL_ENTER("wolfSSL_CTX_set_client_CA_list");
12294
        if (ctx != NULL) {
12295
            wolfSSL_sk_X509_NAME_pop_free(ctx->client_ca_names, NULL);
12296
            ctx->client_ca_names = names;
12297
        }
12298
    }
12299
12300
    void wolfSSL_set_client_CA_list(WOLFSSL* ssl,
12301
                                       WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
12302
    {
12303
        WOLFSSL_ENTER("wolfSSL_set_client_CA_list");
12304
        if (ssl != NULL) {
12305
            if (ssl->client_ca_names != ssl->ctx->client_ca_names)
12306
                wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
12307
            ssl->client_ca_names = names;
12308
        }
12309
    }
12310
12311
    void wolfSSL_CTX_set0_CA_list(WOLFSSL_CTX* ctx,
12312
                                  WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
12313
    {
12314
        WOLFSSL_ENTER("wolfSSL_CTX_set0_CA_list");
12315
        if (ctx != NULL) {
12316
            wolfSSL_sk_X509_NAME_pop_free(ctx->ca_names, NULL);
12317
            ctx->ca_names = names;
12318
        }
12319
    }
12320
12321
    void wolfSSL_set0_CA_list(WOLFSSL* ssl,
12322
                              WOLF_STACK_OF(WOLFSSL_X509_NAME)* names)
12323
    {
12324
        WOLFSSL_ENTER("wolfSSL_set0_CA_list");
12325
        if (ssl != NULL) {
12326
            if (ssl->ca_names != ssl->ctx->ca_names)
12327
                wolfSSL_sk_X509_NAME_pop_free(ssl->ca_names, NULL);
12328
            ssl->ca_names = names;
12329
        }
12330
    }
12331
#endif /* WOLFSSL_NO_CA_NAMES */
12332
12333
#ifdef WOLFSSL_CERT_SETUP_CB
12334
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
12335
    /* registers client cert callback, called during handshake if server
12336
       requests client auth but user has not loaded client cert/key */
12337
    void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb)
12338
    {
12339
        WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb");
12340
12341
        if (ctx != NULL) {
12342
            ctx->CBClientCert = cb;
12343
        }
12344
    }
12345
#endif
12346
12347
    void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx,
12348
        CertSetupCallback cb, void *arg)
12349
    {
12350
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb");
12351
        if (ctx == NULL)
12352
            return;
12353
12354
        ctx->certSetupCb = cb;
12355
        ctx->certSetupCbArg = arg;
12356
    }
12357
12358
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
12359
            const byte** suites, word16* suiteSz,
12360
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
12361
    {
12362
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
12363
12364
        if (suites != NULL)
12365
            *suites = NULL;
12366
        if (suiteSz != NULL)
12367
            *suiteSz = 0;
12368
        if (hashSigAlgo != NULL)
12369
            *hashSigAlgo = NULL;
12370
        if (hashSigAlgoSz != NULL)
12371
            *hashSigAlgoSz = 0;
12372
12373
        if (ssl != NULL && ssl->clSuites != NULL) {
12374
            if (suites != NULL && suiteSz != NULL) {
12375
                *suites = ssl->clSuites->suites;
12376
                *suiteSz = ssl->clSuites->suiteSz;
12377
            }
12378
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
12379
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
12380
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
12381
            }
12382
            return WOLFSSL_SUCCESS;
12383
        }
12384
        return WOLFSSL_FAILURE;
12385
    }
12386
12387
#ifndef NO_TLS
12388
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
12389
            byte second)
12390
    {
12391
        WOLFSSL_CIPHERSUITE_INFO info;
12392
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
12393
                CipherRequires(first, second, REQUIRES_RSA_SIG));
12394
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
12395
                /* Static ECC ciphers may require RSA for authentication */
12396
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
12397
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
12398
        info.eccStatic =
12399
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
12400
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
12401
        return info;
12402
    }
12403
#endif
12404
12405
    /**
12406
     * @param first First byte of the hash and signature algorithm
12407
     * @param second Second byte of the hash and signature algorithm
12408
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
12409
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
12410
     */
12411
    int wolfSSL_get_sigalg_info(byte first, byte second,
12412
            int* hashAlgo, int* sigAlgo)
12413
    {
12414
        byte input[2];
12415
        byte hashType;
12416
        byte sigType;
12417
12418
        if (hashAlgo == NULL || sigAlgo == NULL)
12419
            return BAD_FUNC_ARG;
12420
12421
        input[0] = first;
12422
        input[1] = second;
12423
        DecodeSigAlg(input, &hashType, &sigType);
12424
12425
        /* cast so that compiler reminds us of unimplemented values */
12426
        switch ((enum SignatureAlgorithm)sigType) {
12427
        case anonymous_sa_algo:
12428
            *sigAlgo = ANONk;
12429
            break;
12430
        case rsa_sa_algo:
12431
            *sigAlgo = RSAk;
12432
            break;
12433
        case dsa_sa_algo:
12434
            *sigAlgo = DSAk;
12435
            break;
12436
        case ecc_dsa_sa_algo:
12437
            *sigAlgo = ECDSAk;
12438
            break;
12439
        case rsa_pss_sa_algo:
12440
            *sigAlgo = RSAPSSk;
12441
            break;
12442
        case ed25519_sa_algo:
12443
            *sigAlgo = ED25519k;
12444
            break;
12445
        case rsa_pss_pss_algo:
12446
            *sigAlgo = RSAPSSk;
12447
            break;
12448
        case ed448_sa_algo:
12449
            *sigAlgo = ED448k;
12450
            break;
12451
        case falcon_level1_sa_algo:
12452
            *sigAlgo = FALCON_LEVEL1k;
12453
            break;
12454
        case falcon_level5_sa_algo:
12455
            *sigAlgo = FALCON_LEVEL5k;
12456
            break;
12457
        case dilithium_level2_sa_algo:
12458
            *sigAlgo = ML_DSA_LEVEL2k;
12459
            break;
12460
        case dilithium_level3_sa_algo:
12461
            *sigAlgo = ML_DSA_LEVEL3k;
12462
            break;
12463
        case dilithium_level5_sa_algo:
12464
            *sigAlgo = ML_DSA_LEVEL5k;
12465
            break;
12466
        case sm2_sa_algo:
12467
            *sigAlgo = SM2k;
12468
            break;
12469
        case invalid_sa_algo:
12470
        case any_sa_algo:
12471
        default:
12472
            *hashAlgo = WC_HASH_TYPE_NONE;
12473
            *sigAlgo = 0;
12474
            return BAD_FUNC_ARG;
12475
        }
12476
12477
        /* cast so that compiler reminds us of unimplemented values */
12478
        switch((enum wc_MACAlgorithm)hashType) {
12479
        case no_mac:
12480
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
12481
            *hashAlgo = WC_HASH_TYPE_NONE;
12482
            break;
12483
        case md5_mac:
12484
            *hashAlgo = WC_HASH_TYPE_MD5;
12485
            break;
12486
        case sha_mac:
12487
            *hashAlgo = WC_HASH_TYPE_SHA;
12488
            break;
12489
        case sha224_mac:
12490
            *hashAlgo = WC_HASH_TYPE_SHA224;
12491
            break;
12492
        case sha256_mac:
12493
            *hashAlgo = WC_HASH_TYPE_SHA256;
12494
            break;
12495
        case sha384_mac:
12496
            *hashAlgo = WC_HASH_TYPE_SHA384;
12497
            break;
12498
        case sha512_mac:
12499
            *hashAlgo = WC_HASH_TYPE_SHA512;
12500
            break;
12501
        case blake2b_mac:
12502
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
12503
            break;
12504
        case sm3_mac:
12505
#ifdef WOLFSSL_SM3
12506
            *hashAlgo = WC_HASH_TYPE_SM3;
12507
#else
12508
            *hashAlgo = WC_HASH_TYPE_NONE;
12509
#endif
12510
            break;
12511
        default:
12512
            *hashAlgo = WC_HASH_TYPE_NONE;
12513
            *sigAlgo = 0;
12514
            return BAD_FUNC_ARG;
12515
        }
12516
        return 0;
12517
    }
12518
12519
    /**
12520
     * Internal wrapper for calling certSetupCb
12521
     * @param ssl The SSL/TLS Object
12522
     * @return 0 on success
12523
     */
12524
    int CertSetupCbWrapper(WOLFSSL* ssl)
12525
    {
12526
        int ret = 0;
12527
        if (ssl->ctx->certSetupCb != NULL) {
12528
            WOLFSSL_MSG("Calling user cert setup callback");
12529
            ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg);
12530
            if (ret == 1) {
12531
                WOLFSSL_MSG("User cert callback returned success");
12532
                ret = 0;
12533
            }
12534
            else if (ret == 0) {
12535
                SendAlert(ssl, alert_fatal, internal_error);
12536
                ret = CLIENT_CERT_CB_ERROR;
12537
            }
12538
            else if (ret < 0) {
12539
                ret = WOLFSSL_ERROR_WANT_X509_LOOKUP;
12540
            }
12541
            else {
12542
                WOLFSSL_MSG("Unexpected user callback return");
12543
                ret = CLIENT_CERT_CB_ERROR;
12544
            }
12545
        }
12546
        return ret;
12547
    }
12548
#endif /* WOLFSSL_CERT_SETUP_CB */
12549
12550
#ifndef WOLFSSL_NO_CA_NAMES
12551
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list(
12552
            const WOLFSSL_CTX *ctx)
12553
    {
12554
        WOLFSSL_ENTER("wolfSSL_CTX_get_client_CA_list");
12555
12556
        if (ctx == NULL) {
12557
            WOLFSSL_MSG("Bad argument passed to "
12558
                        "wolfSSL_CTX_get_client_CA_list");
12559
            return NULL;
12560
        }
12561
12562
        return ctx->client_ca_names;
12563
    }
12564
12565
    /* On server side: returns the CAs set via *_set_client_CA_list();
12566
     * On client side: returns the CAs received from server -- same as
12567
     * wolfSSL_get0_peer_CA_list() */
12568
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get_client_CA_list(
12569
            const WOLFSSL* ssl)
12570
    {
12571
        WOLFSSL_ENTER("wolfSSL_get_client_CA_list");
12572
12573
        if (ssl == NULL) {
12574
            WOLFSSL_MSG("Bad argument passed to wolfSSL_get_client_CA_list");
12575
            return NULL;
12576
        }
12577
12578
        if (ssl->options.side == WOLFSSL_CLIENT_END)
12579
            return ssl->peer_ca_names;
12580
        else
12581
            return SSL_CLIENT_CA_NAMES(ssl);
12582
    }
12583
12584
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get0_CA_list(
12585
            const WOLFSSL_CTX *ctx)
12586
    {
12587
        WOLFSSL_ENTER("wolfSSL_CTX_get0_CA_list");
12588
12589
        if (ctx == NULL) {
12590
            WOLFSSL_MSG("Bad argument passed to wolfSSL_CTX_get0_CA_list");
12591
            return NULL;
12592
        }
12593
12594
        return ctx->ca_names;
12595
    }
12596
12597
    /* Always returns the CA's set via *_set0_CA_list */
12598
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get0_CA_list(const WOLFSSL *ssl)
12599
    {
12600
        WOLFSSL_ENTER("wolfSSL_get0_CA_list");
12601
12602
        if (ssl == NULL) {
12603
            WOLFSSL_MSG("Bad argument passed to wolfSSL_get0_CA_list");
12604
            return NULL;
12605
        }
12606
12607
        return SSL_CA_NAMES(ssl);
12608
    }
12609
12610
    /* Always returns the CA's received from the peer */
12611
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get0_peer_CA_list(
12612
            const WOLFSSL* ssl)
12613
    {
12614
        WOLFSSL_ENTER("wolfSSL_get0_peer_CA_list");
12615
12616
        if (ssl == NULL) {
12617
            WOLFSSL_MSG("Bad argument passed to wolfSSL_get0_peer_CA_list");
12618
            return NULL;
12619
        }
12620
12621
        return ssl->peer_ca_names;
12622
    }
12623
12624
    #if !defined(NO_CERTS)
12625
    static int add_to_CA_list(WOLFSSL_STACK* ca_names, WOLFSSL_X509* x509)
12626
    {
12627
        WOLFSSL_X509_NAME *nameCopy = NULL;
12628
12629
        nameCopy = wolfSSL_X509_NAME_dup(wolfSSL_X509_get_subject_name(x509));
12630
        if (nameCopy == NULL) {
12631
            WOLFSSL_MSG("wolfSSL_X509_NAME_dup error");
12632
            return WOLFSSL_FAILURE;
12633
        }
12634
12635
        if (wolfSSL_sk_X509_NAME_push(ca_names, nameCopy) <= 0) {
12636
            WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error");
12637
            wolfSSL_X509_NAME_free(nameCopy);
12638
            return WOLFSSL_FAILURE;
12639
        }
12640
12641
        return WOLFSSL_SUCCESS;
12642
    }
12643
12644
    int wolfSSL_CTX_add_client_CA(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
12645
    {
12646
        WOLFSSL_ENTER("wolfSSL_CTX_add_client_CA");
12647
        if (ctx == NULL || x509 == NULL) {
12648
            WOLFSSL_MSG("Bad argument");
12649
            return WOLFSSL_FAILURE;
12650
        }
12651
        if (ctx->client_ca_names == NULL) {
12652
            ctx->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
12653
            if (ctx->client_ca_names == NULL) {
12654
                WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
12655
                return WOLFSSL_FAILURE;
12656
            }
12657
        }
12658
        return add_to_CA_list(ctx->client_ca_names, x509);
12659
    }
12660
12661
    int wolfSSL_add_client_CA(WOLFSSL* ssl, WOLFSSL_X509* x509)
12662
    {
12663
        WOLFSSL_ENTER("wolfSSL_add_client_CA");
12664
        if (ssl == NULL || x509 == NULL) {
12665
            WOLFSSL_MSG("Bad argument");
12666
            return WOLFSSL_FAILURE;
12667
        }
12668
        if (ssl->client_ca_names == NULL) {
12669
            ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
12670
            if (ssl->client_ca_names == NULL) {
12671
                WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
12672
                return WOLFSSL_FAILURE;
12673
            }
12674
        }
12675
        return add_to_CA_list(ssl->client_ca_names, x509);
12676
    }
12677
12678
    int wolfSSL_CTX_add1_to_CA_list(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509)
12679
    {
12680
        WOLFSSL_ENTER("wolfSSL_CTX_add1_to_CA_list");
12681
        if (ctx == NULL || x509 == NULL) {
12682
            WOLFSSL_MSG("Bad argument");
12683
            return WOLFSSL_FAILURE;
12684
        }
12685
        if (ctx->ca_names == NULL) {
12686
            ctx->ca_names = wolfSSL_sk_X509_NAME_new(NULL);
12687
            if (ctx->ca_names == NULL) {
12688
                WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
12689
                return WOLFSSL_FAILURE;
12690
            }
12691
        }
12692
        return add_to_CA_list(ctx->ca_names, x509);
12693
    }
12694
12695
    int wolfSSL_add1_to_CA_list(WOLFSSL* ssl, WOLFSSL_X509* x509)
12696
    {
12697
        WOLFSSL_ENTER("wolfSSL_add1_to_CA_list");
12698
        if (ssl == NULL || x509 == NULL) {
12699
            WOLFSSL_MSG("Bad argument");
12700
            return WOLFSSL_FAILURE;
12701
        }
12702
        if (ssl->ca_names == NULL) {
12703
            ssl->ca_names = wolfSSL_sk_X509_NAME_new(NULL);
12704
            if (ssl->ca_names == NULL) {
12705
                WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
12706
                return WOLFSSL_FAILURE;
12707
            }
12708
        }
12709
        return add_to_CA_list(ssl->ca_names, x509);
12710
    }
12711
    #endif /* !NO_CERTS */
12712
12713
    #ifndef NO_BIO
12714
        #if !defined(NO_RSA) && !defined(NO_CERTS)
12715
        WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_load_client_CA_file(
12716
            const char* fname)
12717
        {
12718
            /* The webserver build is using this to load a CA into the server
12719
             * for client authentication as an option. Have this return NULL in
12720
             * that case. If OPENSSL_EXTRA is enabled, go ahead and include
12721
             * the function. */
12722
        #ifdef OPENSSL_EXTRA
12723
            WOLFSSL_STACK *list = NULL;
12724
            WOLFSSL_BIO* bio = NULL;
12725
            WOLFSSL_X509 *cert = NULL;
12726
            WOLFSSL_X509_NAME *nameCopy = NULL;
12727
            unsigned long err = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
12728
12729
            WOLFSSL_ENTER("wolfSSL_load_client_CA_file");
12730
12731
            bio = wolfSSL_BIO_new_file(fname, "rb");
12732
            if (bio == NULL) {
12733
                WOLFSSL_MSG("wolfSSL_BIO_new_file error");
12734
                goto cleanup;
12735
            }
12736
12737
            list = wolfSSL_sk_X509_NAME_new(NULL);
12738
            if (list == NULL) {
12739
                WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error");
12740
                goto cleanup;
12741
            }
12742
12743
            /* Read each certificate in the chain out of the file. */
12744
            while (wolfSSL_PEM_read_bio_X509(bio, &cert, NULL, NULL) != NULL) {
12745
                /* Need a persistent copy of the subject name. */
12746
                nameCopy = wolfSSL_X509_NAME_dup(
12747
                        wolfSSL_X509_get_subject_name(cert));
12748
                if (nameCopy == NULL) {
12749
                    WOLFSSL_MSG("wolfSSL_X509_NAME_dup error");
12750
                    goto cleanup;
12751
                }
12752
                /*
12753
                * Original cert will be freed so make sure not to try to access
12754
                * it in the future.
12755
                */
12756
                nameCopy->x509 = NULL;
12757
12758
                if (wolfSSL_sk_X509_NAME_push(list, nameCopy) <= 0) {
12759
                    WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error");
12760
                    /* Do free in loop because nameCopy is now responsibility
12761
                     * of list to free and adding jumps to cleanup after this
12762
                     * might result in a double free. */
12763
                    wolfSSL_X509_NAME_free(nameCopy);
12764
                    goto cleanup;
12765
                }
12766
12767
                wolfSSL_X509_free(cert);
12768
                cert = NULL;
12769
            }
12770
12771
            CLEAR_ASN_NO_PEM_HEADER_ERROR(err);
12772
12773
            err = WOLFSSL_SUCCESS;
12774
cleanup:
12775
            wolfSSL_X509_free(cert);
12776
            cert = NULL;
12777
            wolfSSL_BIO_free(bio);
12778
            if (err != WOLFSSL_SUCCESS) {
12779
                /* We failed so return NULL */
12780
                wolfSSL_sk_X509_NAME_pop_free(list, NULL);
12781
                list = NULL;
12782
            }
12783
            return list;
12784
        #else
12785
            (void)fname;
12786
            return NULL;
12787
        #endif
12788
        }
12789
        #endif
12790
    #endif /* !NO_BIO */
12791
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA */
12792
12793
#ifdef OPENSSL_EXTRA
12794
12795
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
12796
        && !defined(WC_NO_RNG)
12797
    static const byte srp_N[] = {
12798
        0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8,
12799
        0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF,
12800
        0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6,
12801
        0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13,
12802
        0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B,
12803
        0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7,
12804
        0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69,
12805
        0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85,
12806
        0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC,
12807
        0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E,
12808
        0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F,
12809
        0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3
12810
    };
12811
    static const byte srp_g[] = {
12812
        0x02
12813
    };
12814
12815
    int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username)
12816
    {
12817
        int r = 0;
12818
        SrpSide srp_side = SRP_CLIENT_SIDE;
12819
12820
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username");
12821
        if (ctx == NULL || ctx->srp == NULL || username==NULL)
12822
            return WOLFSSL_FAILURE;
12823
12824
        if (ctx->method->side == WOLFSSL_SERVER_END){
12825
            srp_side = SRP_SERVER_SIDE;
12826
        } else if (ctx->method->side == WOLFSSL_CLIENT_END){
12827
            srp_side = SRP_CLIENT_SIDE;
12828
        } else {
12829
            WOLFSSL_MSG("Init CTX failed");
12830
            return WOLFSSL_FAILURE;
12831
        }
12832
12833
        if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) {
12834
            WOLFSSL_MSG("Init SRP CTX failed");
12835
            XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
12836
            ctx->srp = NULL;
12837
            return WOLFSSL_FAILURE;
12838
        }
12839
        r = wc_SrpSetUsername(ctx->srp, (const byte*)username,
12840
                              (word32)XSTRLEN(username));
12841
        if (r < 0) {
12842
            WOLFSSL_MSG("fail to set srp username.");
12843
            return WOLFSSL_FAILURE;
12844
        }
12845
12846
        /* if wolfSSL_CTX_set_srp_password has already been called, */
12847
        /* use saved password here */
12848
        if (ctx->srp_password != NULL) {
12849
            if (ctx->srp->user == NULL)
12850
                return WOLFSSL_FAILURE;
12851
            return wolfSSL_CTX_set_srp_password(ctx, (char*)ctx->srp_password);
12852
        }
12853
12854
        return WOLFSSL_SUCCESS;
12855
    }
12856
12857
    int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password)
12858
    {
12859
        int r;
12860
        byte salt[SRP_SALT_SIZE];
12861
12862
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password");
12863
        if (ctx == NULL || ctx->srp == NULL || password == NULL)
12864
            return WOLFSSL_FAILURE;
12865
12866
        if (ctx->srp->user != NULL) {
12867
            WC_RNG rng;
12868
            if (wc_InitRng(&rng) < 0) {
12869
                WOLFSSL_MSG("wc_InitRng failed");
12870
                return WOLFSSL_FAILURE;
12871
            }
12872
            XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0]));
12873
            r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0]));
12874
            wc_FreeRng(&rng);
12875
            if (r <  0) {
12876
                WOLFSSL_MSG("wc_RNG_GenerateBlock failed");
12877
                return WOLFSSL_FAILURE;
12878
            }
12879
            if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]),
12880
                                srp_g, sizeof(srp_g)/sizeof(srp_g[0]),
12881
                                salt, sizeof(salt)/sizeof(salt[0])) < 0){
12882
                WOLFSSL_MSG("wc_SrpSetParam failed");
12883
                return WOLFSSL_FAILURE;
12884
            }
12885
            r = wc_SrpSetPassword(ctx->srp, (const byte*)password,
12886
                                  (word32)XSTRLEN(password));
12887
            if (r < 0) {
12888
                WOLFSSL_MSG("wc_SrpSetPassword failed.");
12889
                return WOLFSSL_FAILURE;
12890
            }
12891
            XFREE(ctx->srp_password, NULL, DYNAMIC_TYPE_SRP);
12892
            ctx->srp_password = NULL;
12893
        } else {
12894
            /* save password for wolfSSL_set_srp_username */
12895
            XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
12896
12897
            ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap,
12898
                                               DYNAMIC_TYPE_SRP);
12899
            if (ctx->srp_password == NULL){
12900
                WOLFSSL_MSG("memory allocation error");
12901
                return WOLFSSL_FAILURE;
12902
            }
12903
            XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1);
12904
        }
12905
        return WOLFSSL_SUCCESS;
12906
    }
12907
12908
    /**
12909
     * The modulus passed to wc_SrpSetParams in ssl.c is constant so check
12910
     * that the requested strength is less than or equal to the size of the
12911
     * static modulus size.
12912
     * @param ctx Not used
12913
     * @param strength Minimum number of bits for the modulus
12914
     * @return 1 if strength is less than or equal to static modulus
12915
     *         0 if strength is greater than static modulus
12916
     */
12917
    int  wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength)
12918
    {
12919
        (void)ctx;
12920
        WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength");
12921
        if (strength > (int)(sizeof(srp_N)*8)) {
12922
            WOLFSSL_MSG("Bad Parameter");
12923
            return WOLFSSL_FAILURE;
12924
        }
12925
        return WOLFSSL_SUCCESS;
12926
    }
12927
12928
    char* wolfSSL_get_srp_username(WOLFSSL *ssl)
12929
    {
12930
        if (ssl && ssl->ctx && ssl->ctx->srp) {
12931
            return (char*) ssl->ctx->srp->user;
12932
        }
12933
        return NULL;
12934
    }
12935
    #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */
12936
12937
    /* keyblock size in bytes or -1 */
12938
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
12939
    {
12940
        if (ssl == NULL)
12941
            return WOLFSSL_FATAL_ERROR;
12942
12943
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
12944
                    ssl->specs.hash_size);
12945
    }
12946
12947
#endif /* OPENSSL_EXTRA */
12948
12949
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
12950
    defined(WOLFSSL_WPAS_SMALL)
12951
12952
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
12953
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
12954
                                     unsigned char** sr, unsigned int* srLen,
12955
                                     unsigned char** cr, unsigned int* crLen)
12956
    {
12957
        if (ssl == NULL || ssl->arrays == NULL)
12958
            return WOLFSSL_FATAL_ERROR;
12959
12960
        *ms = ssl->arrays->masterSecret;
12961
        *sr = ssl->arrays->serverRandom;
12962
        *cr = ssl->arrays->clientRandom;
12963
12964
        *msLen = SECRET_LEN;
12965
        *srLen = RAN_LEN;
12966
        *crLen = RAN_LEN;
12967
12968
        return WOLFSSL_SUCCESS;
12969
    }
12970
12971
    void wolfSSL_set_accept_state(WOLFSSL* ssl)
12972
    {
12973
        WOLFSSL_ENTER("wolfSSL_set_accept_state");
12974
12975
        if (ssl == NULL)
12976
            return;
12977
12978
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
12979
    #ifdef HAVE_ECC
12980
            WC_DECLARE_VAR(key, ecc_key, 1, 0);
12981
            word32 idx = 0;
12982
12983
        #ifdef WOLFSSL_SMALL_STACK
12984
            key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
12985
                                    DYNAMIC_TYPE_ECC);
12986
            if (key == NULL) {
12987
                WOLFSSL_MSG("Error allocating memory for ecc_key");
12988
            }
12989
        #endif
12990
            if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) {
12991
                if (wc_ecc_init(key) >= 0) {
12992
                    if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
12993
                            key, ssl->buffers.key->length) != 0) {
12994
                        ssl->options.haveECDSAsig = 0;
12995
                        ssl->options.haveECC = 0;
12996
                        ssl->options.haveStaticECC = 0;
12997
                    }
12998
                    wc_ecc_free(key);
12999
                }
13000
            }
13001
            WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
13002
    #endif
13003
13004
    #ifndef NO_DH
13005
            if (!ssl->options.haveDH && ssl->ctx->haveDH) {
13006
                ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
13007
                ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
13008
                ssl->options.haveDH = 1;
13009
            }
13010
    #endif
13011
        }
13012
13013
        if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
13014
            WOLFSSL_MSG("Error initializing server side");
13015
        }
13016
    }
13017
13018
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
13019
13020
    /* return true if connection established */
13021
    /* this works for TLS and DTLS */
13022
    int wolfSSL_is_init_finished(const WOLFSSL* ssl)
13023
0
    {
13024
0
        if (ssl == NULL)
13025
0
            return 0;
13026
13027
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_CLIENT)
13028
        if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls
13029
                && IsAtLeastTLSv1_3(ssl->version)) {
13030
            return ssl->options.serverState == SERVER_FINISHED_ACKED;
13031
        }
13032
#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT */
13033
13034
        /* Can't use ssl->options.connectState and ssl->options.acceptState
13035
         * because they differ in meaning for TLS <=1.2 and 1.3 */
13036
0
        if (ssl->options.handShakeState == HANDSHAKE_DONE)
13037
0
            return 1;
13038
13039
0
        return 0;
13040
0
    }
13041
13042
#ifdef OPENSSL_EXTRA
13043
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
13044
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
13045
    {
13046
        /* wolfSSL verifies all these internally */
13047
        (void)ctx;
13048
        (void)f;
13049
    }
13050
13051
13052
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
13053
    {
13054
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
13055
        if(ssl==NULL) {
13056
            WOLFSSL_MSG("Shutdown not set. ssl is null");
13057
            return;
13058
        }
13059
13060
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
13061
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
13062
    }
13063
#endif
13064
13065
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
13066
0
    {
13067
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
13068
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
13069
0
        if(ctx == NULL)
13070
0
            return BAD_FUNC_ARG;
13071
0
        return (long)ctx->mask;
13072
0
    }
13073
13074
    /* forward declaration */
13075
    static long wolf_set_options(long old_op, long op);
13076
13077
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
13078
0
    {
13079
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
13080
13081
0
        if (ctx == NULL)
13082
0
            return BAD_FUNC_ARG;
13083
13084
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
13085
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
13086
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
13087
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
13088
          ctx->noTicketTls12 = 1;
13089
        }
13090
        /* This code is here for documentation purpose. You must not turn off
13091
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
13092
         * Because we need to support both stateful and stateless tickets.
13093
        #ifdef WOLFSSL_TLS13
13094
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
13095
                ctx->noTicketTls13 = 1;
13096
            }
13097
        #endif
13098
        */
13099
#endif
13100
0
        return (long)ctx->mask;
13101
0
    }
13102
13103
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
13104
0
    {
13105
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
13106
0
        if(ctx == NULL)
13107
0
            return BAD_FUNC_ARG;
13108
0
        ctx->mask &= (unsigned long)~opt;
13109
0
        return (long)ctx->mask;
13110
0
    }
13111
13112
#ifdef OPENSSL_EXTRA
13113
13114
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
13115
    {
13116
        WOLFSSL_ENTER("wolfSSL_set_rfd");
13117
        ssl->rfd = rfd;      /* not used directly to allow IO callbacks */
13118
13119
        ssl->IOCB_ReadCtx  = &ssl->rfd;
13120
13121
    #ifdef WOLFSSL_DTLS
13122
        if (ssl->options.dtls) {
13123
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
13124
            ssl->buffers.dtlsCtx.rfd = rfd;
13125
        }
13126
    #endif
13127
13128
        return WOLFSSL_SUCCESS;
13129
    }
13130
13131
13132
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
13133
    {
13134
        WOLFSSL_ENTER("wolfSSL_set_wfd");
13135
        ssl->wfd = wfd;      /* not used directly to allow IO callbacks */
13136
13137
        ssl->IOCB_WriteCtx  = &ssl->wfd;
13138
13139
        return WOLFSSL_SUCCESS;
13140
    }
13141
#endif /* OPENSSL_EXTRA */
13142
13143
#if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || \
13144
    defined(WOLFSSL_WPAS_SMALL))
13145
13146
    WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(const WOLFSSL_CTX* ctx)
13147
    {
13148
        if (ctx == NULL) {
13149
            return NULL;
13150
        }
13151
13152
        if (ctx->x509_store_pt != NULL)
13153
            return ctx->x509_store_pt;
13154
        return &((WOLFSSL_CTX*)ctx)->x509_store;
13155
    }
13156
13157
    void wolfSSL_CTX_set_cert_store(WOLFSSL_CTX* ctx, WOLFSSL_X509_STORE* str)
13158
    {
13159
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_store");
13160
        if (ctx == NULL || str == NULL || ctx->cm == str->cm) {
13161
            return;
13162
        }
13163
13164
        if (wolfSSL_CertManager_up_ref(str->cm) != WOLFSSL_SUCCESS) {
13165
            WOLFSSL_MSG("wolfSSL_CertManager_up_ref error");
13166
            return;
13167
        }
13168
        /* free cert manager if have one */
13169
        if (ctx->cm != NULL) {
13170
            wolfSSL_CertManagerFree(ctx->cm);
13171
        }
13172
        ctx->cm               = str->cm;
13173
        ctx->x509_store.cm    = str->cm;
13174
13175
        /* free existing store if it exists */
13176
        wolfSSL_X509_STORE_free(ctx->x509_store_pt);
13177
        ctx->x509_store.cache = str->cache;
13178
        ctx->x509_store_pt    = str; /* take ownership of store and free it
13179
                                        with CTX free */
13180
        ctx->cm->x509_store_p = ctx->x509_store_pt;/* CTX has ownership
13181
                                                    and free it with CTX free*/
13182
    }
13183
13184
#ifdef OPENSSL_ALL
13185
    int wolfSSL_CTX_set1_verify_cert_store(WOLFSSL_CTX* ctx,
13186
        WOLFSSL_X509_STORE* str)
13187
    {
13188
        WOLFSSL_ENTER("wolfSSL_CTX_set1_verify_cert_store");
13189
13190
        if (ctx == NULL || str == NULL) {
13191
            WOLFSSL_MSG("Bad parameter");
13192
            return WOLFSSL_FAILURE;
13193
        }
13194
13195
        /* NO-OP when setting existing store */
13196
        if (str == CTX_STORE(ctx))
13197
            return WOLFSSL_SUCCESS;
13198
13199
        if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) {
13200
            WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error");
13201
            return WOLFSSL_FAILURE;
13202
        }
13203
13204
        /* free existing store if it exists */
13205
        wolfSSL_X509_STORE_free(ctx->x509_store_pt);
13206
        ctx->x509_store_pt = str; /* take ownership of store and free it
13207
                                     with CTX free */
13208
        return WOLFSSL_SUCCESS;
13209
    }
13210
#endif
13211
13212
    int wolfSSL_set0_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str)
13213
    {
13214
        WOLFSSL_ENTER("wolfSSL_set0_verify_cert_store");
13215
13216
        if (ssl == NULL || str == NULL) {
13217
            WOLFSSL_MSG("Bad parameter");
13218
            return WOLFSSL_FAILURE;
13219
        }
13220
13221
        /* NO-OP when setting existing store */
13222
        if (str == SSL_STORE(ssl))
13223
            return WOLFSSL_SUCCESS;
13224
13225
        /* free existing store if it exists */
13226
        wolfSSL_X509_STORE_free(ssl->x509_store_pt);
13227
        if (str == ssl->ctx->x509_store_pt)
13228
            ssl->x509_store_pt = NULL; /* if setting ctx store then just revert
13229
                                          to using that instead */
13230
        else
13231
            ssl->x509_store_pt = str; /* take ownership of store and free it
13232
                                         with SSL free */
13233
        return WOLFSSL_SUCCESS;
13234
    }
13235
13236
13237
    int wolfSSL_set1_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str)
13238
    {
13239
        WOLFSSL_ENTER("wolfSSL_set1_verify_cert_store");
13240
13241
        if (ssl == NULL || str == NULL) {
13242
            WOLFSSL_MSG("Bad parameter");
13243
            return WOLFSSL_FAILURE;
13244
        }
13245
13246
        /* NO-OP when setting existing store */
13247
        if (str == SSL_STORE(ssl))
13248
            return WOLFSSL_SUCCESS;
13249
13250
        if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) {
13251
            WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error");
13252
            return WOLFSSL_FAILURE;
13253
        }
13254
13255
        /* free existing store if it exists */
13256
        wolfSSL_X509_STORE_free(ssl->x509_store_pt);
13257
        if (str == ssl->ctx->x509_store_pt)
13258
            ssl->x509_store_pt = NULL; /* if setting ctx store then just revert
13259
                                          to using that instead */
13260
        else
13261
            ssl->x509_store_pt = str; /* take ownership of store and free it
13262
                                         with SSL free */
13263
        return WOLFSSL_SUCCESS;
13264
    }
13265
#endif /* !NO_CERTS && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */
13266
13267
#ifdef WOLFSSL_ENCRYPTED_KEYS
13268
13269
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
13270
                                                   void* userdata)
13271
    {
13272
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
13273
        if (ctx)
13274
            ctx->passwd_userdata = userdata;
13275
    }
13276
13277
13278
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
13279
                                           cb)
13280
    {
13281
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
13282
        if (ctx)
13283
            ctx->passwd_cb = cb;
13284
    }
13285
13286
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
13287
    {
13288
        if (ctx == NULL || ctx->passwd_cb == NULL) {
13289
            return NULL;
13290
        }
13291
13292
        return ctx->passwd_cb;
13293
    }
13294
13295
13296
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
13297
    {
13298
        if (ctx == NULL) {
13299
            return NULL;
13300
        }
13301
13302
        return ctx->passwd_userdata;
13303
    }
13304
13305
#endif /* WOLFSSL_ENCRYPTED_KEYS */
13306
13307
13308
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
13309
    unsigned long wolfSSL_ERR_get_error(void)
13310
    {
13311
        WOLFSSL_ENTER("wolfSSL_ERR_get_error");
13312
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
13313
        return (unsigned long)wc_GetErrorNodeErr();
13314
#else
13315
        return (unsigned long)(0 - NOT_COMPILED_IN);
13316
#endif
13317
    }
13318
#endif
13319
13320
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
13321
13322
    int wolfSSL_num_locks(void)
13323
    {
13324
        return 0;
13325
    }
13326
13327
    void wolfSSL_set_locking_callback(mutex_cb* f)
13328
    {
13329
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
13330
13331
        if (wc_SetMutexCb(f) != 0) {
13332
            WOLFSSL_MSG("Error when setting mutex call back");
13333
        }
13334
    }
13335
13336
    mutex_cb* wolfSSL_get_locking_callback(void)
13337
    {
13338
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
13339
13340
        return wc_GetMutexCb();
13341
    }
13342
13343
13344
    typedef unsigned long (idCb)(void);
13345
    static idCb* inner_idCb = NULL;
13346
13347
    unsigned long wolfSSL_thread_id(void)
13348
    {
13349
        if (inner_idCb != NULL) {
13350
            return inner_idCb();
13351
        }
13352
        else {
13353
            return 0;
13354
        }
13355
    }
13356
13357
13358
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
13359
    {
13360
        inner_idCb = f;
13361
    }
13362
13363
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
13364
#ifndef NO_BIO
13365
    /* print out and clear all errors */
13366
    void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio)
13367
    {
13368
        const char* file = NULL;
13369
        const char* reason = NULL;
13370
        int ret;
13371
        int line = 0;
13372
        char buf[WOLFSSL_MAX_ERROR_SZ * 2];
13373
13374
        WOLFSSL_ENTER("wolfSSL_ERR_print_errors");
13375
13376
        if (bio == NULL) {
13377
            WOLFSSL_MSG("BIO passed in was null");
13378
            return;
13379
        }
13380
13381
        do {
13382
        ret = wc_PeekErrorNode(0, &file, &reason, &line);
13383
        if (ret >= 0) {
13384
            const char* r = wolfSSL_ERR_reason_error_string(
13385
                (unsigned long)(0 - ret));
13386
            if (XSNPRINTF(buf, sizeof(buf),
13387
                          "error:%d:wolfSSL library:%s:%s:%d\n",
13388
                          ret, r, file, line)
13389
                >= (int)sizeof(buf))
13390
            {
13391
                WOLFSSL_MSG("Buffer overrun formatting error message");
13392
            }
13393
            wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf));
13394
            wc_RemoveErrorNode(0);
13395
        }
13396
        } while (ret >= 0);
13397
        if (wolfSSL_BIO_write(bio, "", 1) != 1) {
13398
            WOLFSSL_MSG("Issue writing final string terminator");
13399
        }
13400
    }
13401
#endif /* !NO_BIO */
13402
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
13403
13404
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
13405
13406
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
13407
    defined(HAVE_SECRET_CALLBACK)
13408
#if !defined(NO_WOLFSSL_SERVER)
13409
/* Return the amount of random bytes copied over or error case.
13410
 * ssl : ssl struct after handshake
13411
 * out : buffer to hold random bytes
13412
 * outSz : either 0 (return max buffer sz) or size of out buffer
13413
 */
13414
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
13415
                                                                   size_t outSz)
13416
{
13417
    size_t size;
13418
13419
    /* return max size of buffer */
13420
    if (outSz == 0) {
13421
        return RAN_LEN;
13422
    }
13423
13424
    if (ssl == NULL || out == NULL) {
13425
        return 0;
13426
    }
13427
13428
    if (ssl->arrays == NULL) {
13429
        WOLFSSL_MSG("Arrays struct not saved after handshake");
13430
        return 0;
13431
    }
13432
13433
    if (outSz > RAN_LEN) {
13434
        size = RAN_LEN;
13435
    }
13436
    else {
13437
        size = outSz;
13438
    }
13439
13440
    XMEMCPY(out, ssl->arrays->serverRandom, size);
13441
    return size;
13442
}
13443
#endif /* !NO_WOLFSSL_SERVER */
13444
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
13445
13446
#ifdef OPENSSL_EXTRA
13447
#if !defined(NO_WOLFSSL_SERVER)
13448
/* Used to get the peer ephemeral public key sent during the connection
13449
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
13450
 *       before the ephemeral key is stored.
13451
 * return WOLFSSL_SUCCESS on success */
13452
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
13453
{
13454
    WOLFSSL_EVP_PKEY* ret = NULL;
13455
13456
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
13457
13458
    if (ssl == NULL || pkey == NULL) {
13459
        WOLFSSL_MSG("Bad argument passed in");
13460
        return WOLFSSL_FAILURE;
13461
    }
13462
13463
#ifdef HAVE_ECC
13464
    if (ssl->peerEccKey != NULL) {
13465
        unsigned char* der;
13466
        const unsigned char* pt;
13467
        unsigned int   derSz = 0;
13468
        int sz;
13469
13470
        PRIVATE_KEY_UNLOCK();
13471
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
13472
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
13473
        {
13474
            WOLFSSL_MSG("get ecc der size failed");
13475
            PRIVATE_KEY_LOCK();
13476
            return WOLFSSL_FAILURE;
13477
        }
13478
        PRIVATE_KEY_LOCK();
13479
13480
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
13481
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
13482
        if (der == NULL) {
13483
            WOLFSSL_MSG("Memory error");
13484
            return WOLFSSL_FAILURE;
13485
        }
13486
13487
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
13488
            WOLFSSL_MSG("get ecc der failed");
13489
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
13490
            return WOLFSSL_FAILURE;
13491
        }
13492
        pt = der; /* in case pointer gets advanced */
13493
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
13494
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
13495
    }
13496
#endif
13497
13498
    *pkey = ret;
13499
#ifdef HAVE_ECC
13500
    if (ret != NULL)
13501
        return WOLFSSL_SUCCESS;
13502
    else
13503
#endif
13504
        return WOLFSSL_FAILURE;
13505
}
13506
13507
#endif /* !NO_WOLFSSL_SERVER */
13508
13509
/**
13510
 * This function checks if any compiled in protocol versions are
13511
 * left enabled after calls to set_min or set_max API.
13512
 * @param major The SSL/TLS major version
13513
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
13514
 *         protocol versions are left enabled.
13515
 */
13516
static int CheckSslMethodVersion(byte major, unsigned long options)
13517
{
13518
    int sanityConfirmed = 0;
13519
13520
    (void)options;
13521
13522
    switch (major) {
13523
    #ifndef NO_TLS
13524
        case SSLv3_MAJOR:
13525
            #ifdef WOLFSSL_ALLOW_SSLV3
13526
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
13527
                    sanityConfirmed = 1;
13528
                }
13529
            #endif
13530
            #ifndef NO_OLD_TLS
13531
                if (!(options & WOLFSSL_OP_NO_TLSv1))
13532
                    sanityConfirmed = 1;
13533
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
13534
                    sanityConfirmed = 1;
13535
            #endif
13536
            #ifndef WOLFSSL_NO_TLS12
13537
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
13538
                    sanityConfirmed = 1;
13539
            #endif
13540
            #ifdef WOLFSSL_TLS13
13541
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
13542
                    sanityConfirmed = 1;
13543
            #endif
13544
            break;
13545
    #endif
13546
    #ifdef WOLFSSL_DTLS
13547
        case DTLS_MAJOR:
13548
            sanityConfirmed = 1;
13549
            break;
13550
    #endif
13551
        default:
13552
            WOLFSSL_MSG("Invalid major version");
13553
            return WOLFSSL_FAILURE;
13554
    }
13555
    if (!sanityConfirmed) {
13556
        WOLFSSL_MSG("All compiled in TLS versions disabled");
13557
        return WOLFSSL_FAILURE;
13558
    }
13559
    return WOLFSSL_SUCCESS;
13560
}
13561
13562
/**
13563
 * protoVerTbl holds (D)TLS version numbers in ascending order.
13564
 * Except DTLS versions, the newer version is located in the latter part of
13565
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
13566
 * wolfSSL_CTX_set_max_proto_version.
13567
 */
13568
static const int protoVerTbl[] = {
13569
    SSL3_VERSION,
13570
    TLS1_VERSION,
13571
    TLS1_1_VERSION,
13572
    TLS1_2_VERSION,
13573
    TLS1_3_VERSION,
13574
    DTLS1_VERSION,
13575
    DTLS1_2_VERSION
13576
};
13577
/* number of protocol versions listed in protoVerTbl */
13578
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
13579
13580
/**
13581
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
13582
 * version to use by SSL objects created from this WOLFSSL_CTX.
13583
 * This API guarantees that a version of SSL/TLS lower than specified
13584
 * here will not be allowed. If the version specified is not compiled in
13585
 * then this API sets the lowest compiled in protocol version.
13586
 * This API also accept 0 as version, to set the minimum version automatically.
13587
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
13588
 * are enabled.
13589
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
13590
 * @param version Any of the following
13591
 *          * 0
13592
 *          * SSL3_VERSION
13593
 *          * TLS1_VERSION
13594
 *          * TLS1_1_VERSION
13595
 *          * TLS1_2_VERSION
13596
 *          * TLS1_3_VERSION
13597
 *          * DTLS1_VERSION
13598
 *          * DTLS1_2_VERSION
13599
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
13600
 *         protocol versions are left enabled.
13601
 */
13602
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
13603
{
13604
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
13605
13606
    if (ctx == NULL) {
13607
        return WOLFSSL_FAILURE;
13608
    }
13609
13610
    switch (version) {
13611
#ifndef NO_TLS
13612
        case SSL3_VERSION:
13613
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
13614
            ctx->minDowngrade = SSLv3_MINOR;
13615
            break;
13616
#endif
13617
        case TLS1_VERSION:
13618
        #ifdef WOLFSSL_ALLOW_TLSV10
13619
            ctx->minDowngrade = TLSv1_MINOR;
13620
            break;
13621
        #endif
13622
        case TLS1_1_VERSION:
13623
        #ifndef NO_OLD_TLS
13624
            ctx->minDowngrade = TLSv1_1_MINOR;
13625
            break;
13626
        #endif
13627
        case TLS1_2_VERSION:
13628
        #ifndef WOLFSSL_NO_TLS12
13629
            ctx->minDowngrade = TLSv1_2_MINOR;
13630
            break;
13631
        #endif
13632
        case TLS1_3_VERSION:
13633
        #ifdef WOLFSSL_TLS13
13634
            ctx->minDowngrade = TLSv1_3_MINOR;
13635
            break;
13636
        #endif
13637
#endif
13638
#ifdef WOLFSSL_DTLS
13639
        case DTLS1_VERSION:
13640
    #ifndef NO_OLD_TLS
13641
            ctx->minDowngrade = DTLS_MINOR;
13642
            break;
13643
    #endif
13644
        case DTLS1_2_VERSION:
13645
            ctx->minDowngrade = DTLSv1_2_MINOR;
13646
            break;
13647
#endif
13648
        default:
13649
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13650
            return WOLFSSL_FAILURE;
13651
    }
13652
13653
    switch (version) {
13654
#ifndef NO_TLS
13655
    case TLS1_3_VERSION:
13656
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
13657
        FALL_THROUGH;
13658
    case TLS1_2_VERSION:
13659
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
13660
        FALL_THROUGH;
13661
    case TLS1_1_VERSION:
13662
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
13663
        FALL_THROUGH;
13664
    case TLS1_VERSION:
13665
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
13666
        break;
13667
    case SSL3_VERSION:
13668
    case SSL2_VERSION:
13669
        /* Nothing to do here */
13670
        break;
13671
#endif
13672
#ifdef WOLFSSL_DTLS
13673
    case DTLS1_VERSION:
13674
    case DTLS1_2_VERSION:
13675
        break;
13676
#endif
13677
    default:
13678
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13679
        return WOLFSSL_FAILURE;
13680
    }
13681
13682
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
13683
}
13684
13685
/* Sets the min protocol version allowed with WOLFSSL_CTX
13686
 * returns WOLFSSL_SUCCESS on success */
13687
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
13688
{
13689
    int ret;
13690
    int proto    = 0;
13691
    int maxProto = 0;
13692
    int i;
13693
    int idx = 0;
13694
13695
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
13696
13697
    if (ctx == NULL) {
13698
        return WOLFSSL_FAILURE;
13699
    }
13700
13701
    if (version != 0) {
13702
        proto = version;
13703
        ctx->minProto = 0; /* turn min proto flag off */
13704
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
13705
            if (protoVerTbl[i] == version) {
13706
                break;
13707
            }
13708
        }
13709
    }
13710
    else {
13711
        /* when 0 is specified as version, try to find out the min version */
13712
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
13713
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
13714
            if (ret == WOLFSSL_SUCCESS) {
13715
                proto = protoVerTbl[i];
13716
                ctx->minProto = 1; /* turn min proto flag on */
13717
                break;
13718
            }
13719
        }
13720
    }
13721
13722
    /* check case where max > min , if so then clear the NO_* options
13723
     * i is the index into the table for proto version used, see if the max
13724
     * proto version index found is smaller */
13725
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
13726
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
13727
        if (protoVerTbl[idx] == maxProto) {
13728
            break;
13729
        }
13730
    }
13731
    if (idx < i) {
13732
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
13733
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
13734
                WOLFSSL_OP_NO_TLSv1_3);
13735
    }
13736
13737
    ret = Set_CTX_min_proto_version(ctx, proto);
13738
    return ret;
13739
}
13740
13741
/**
13742
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
13743
 * version to use by SSL objects created from this WOLFSSL_CTX.
13744
 * This API guarantees that a version of SSL/TLS higher than specified
13745
 * here will not be allowed. If the version specified is not compiled in
13746
 * then this API sets the highest compiled in protocol version.
13747
 * This API also accept 0 as version, to set the maximum version automatically.
13748
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
13749
 * are enabled.
13750
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
13751
 * @param ver Any of the following
13752
 *          * 0
13753
 *          * SSL3_VERSION
13754
 *          * TLS1_VERSION
13755
 *          * TLS1_1_VERSION
13756
 *          * TLS1_2_VERSION
13757
 *          * TLS1_3_VERSION
13758
 *          * DTLS1_VERSION
13759
 *          * DTLS1_2_VERSION
13760
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
13761
 *         protocol versions are left enabled.
13762
 */
13763
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
13764
{
13765
    int ret;
13766
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
13767
13768
    if (!ctx || !ctx->method) {
13769
        WOLFSSL_MSG("Bad parameter");
13770
        return WOLFSSL_FAILURE;
13771
    }
13772
13773
    switch (ver) {
13774
#ifndef NO_TLS
13775
#ifndef NO_OLD_TLS
13776
    case SSL2_VERSION:
13777
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
13778
        return WOLFSSL_FAILURE;
13779
#endif
13780
    case SSL3_VERSION:
13781
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
13782
        FALL_THROUGH;
13783
    case TLS1_VERSION:
13784
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
13785
        FALL_THROUGH;
13786
    case TLS1_1_VERSION:
13787
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
13788
        FALL_THROUGH;
13789
    case TLS1_2_VERSION:
13790
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
13791
        FALL_THROUGH;
13792
    case TLS1_3_VERSION:
13793
        /* Nothing to do here */
13794
        break;
13795
#endif
13796
#ifdef WOLFSSL_DTLS
13797
    case DTLS1_VERSION:
13798
    case DTLS1_2_VERSION:
13799
        break;
13800
#endif
13801
    default:
13802
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13803
        return WOLFSSL_FAILURE;
13804
    }
13805
13806
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
13807
    if (ret == WOLFSSL_SUCCESS) {
13808
        /* Check the major */
13809
        switch (ver) {
13810
    #ifndef NO_TLS
13811
        case SSL3_VERSION:
13812
        case TLS1_VERSION:
13813
        case TLS1_1_VERSION:
13814
        case TLS1_2_VERSION:
13815
        case TLS1_3_VERSION:
13816
            if (ctx->method->version.major != SSLv3_MAJOR) {
13817
                WOLFSSL_MSG("Mismatched protocol version");
13818
                return WOLFSSL_FAILURE;
13819
            }
13820
            break;
13821
    #endif
13822
    #ifdef WOLFSSL_DTLS
13823
        case DTLS1_VERSION:
13824
        case DTLS1_2_VERSION:
13825
            if (ctx->method->version.major != DTLS_MAJOR) {
13826
                WOLFSSL_MSG("Mismatched protocol version");
13827
                return WOLFSSL_FAILURE;
13828
            }
13829
            break;
13830
    #endif
13831
        }
13832
        /* Update the method */
13833
        switch (ver) {
13834
    #ifndef NO_TLS
13835
        case SSL3_VERSION:
13836
            ctx->method->version.minor = SSLv3_MINOR;
13837
            break;
13838
        case TLS1_VERSION:
13839
            ctx->method->version.minor = TLSv1_MINOR;
13840
            break;
13841
        case TLS1_1_VERSION:
13842
            ctx->method->version.minor = TLSv1_1_MINOR;
13843
            break;
13844
        case TLS1_2_VERSION:
13845
            ctx->method->version.minor = TLSv1_2_MINOR;
13846
            break;
13847
        case TLS1_3_VERSION:
13848
            ctx->method->version.minor = TLSv1_3_MINOR;
13849
            break;
13850
    #endif
13851
    #ifdef WOLFSSL_DTLS
13852
        case DTLS1_VERSION:
13853
            ctx->method->version.minor = DTLS_MINOR;
13854
            break;
13855
        case DTLS1_2_VERSION:
13856
            ctx->method->version.minor = DTLSv1_2_MINOR;
13857
            break;
13858
    #endif
13859
        default:
13860
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13861
            return WOLFSSL_FAILURE;
13862
        }
13863
    }
13864
    return ret;
13865
}
13866
13867
13868
/* Sets the max protocol version allowed with WOLFSSL_CTX
13869
 * returns WOLFSSL_SUCCESS on success */
13870
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
13871
{
13872
    int i;
13873
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
13874
    int minProto;
13875
13876
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
13877
13878
    if (ctx == NULL) {
13879
        return ret;
13880
    }
13881
13882
    /* clear out flags and reset min protocol version */
13883
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
13884
    wolfSSL_CTX_clear_options(ctx,
13885
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
13886
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
13887
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
13888
    if (version != 0) {
13889
        ctx->maxProto = 0; /* turn max proto flag off */
13890
        return Set_CTX_max_proto_version(ctx, version);
13891
    }
13892
13893
    /* when 0 is specified as version, try to find out the min version from
13894
     * the bottom to top of the protoverTbl.
13895
     */
13896
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
13897
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
13898
        if (ret == WOLFSSL_SUCCESS) {
13899
            ctx->maxProto = 1; /* turn max proto flag on */
13900
            break;
13901
        }
13902
    }
13903
13904
    return ret;
13905
}
13906
13907
13908
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
13909
{
13910
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
13911
13912
    if (ssl == NULL) {
13913
        return WOLFSSL_FAILURE;
13914
    }
13915
13916
    switch (ver) {
13917
#ifndef NO_TLS
13918
        case SSL3_VERSION:
13919
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
13920
            ssl->options.minDowngrade = SSLv3_MINOR;
13921
            break;
13922
#endif
13923
        case TLS1_VERSION:
13924
        #ifdef WOLFSSL_ALLOW_TLSV10
13925
            ssl->options.minDowngrade = TLSv1_MINOR;
13926
            break;
13927
        #endif
13928
        case TLS1_1_VERSION:
13929
        #ifndef NO_OLD_TLS
13930
            ssl->options.minDowngrade = TLSv1_1_MINOR;
13931
            break;
13932
        #endif
13933
        case TLS1_2_VERSION:
13934
        #ifndef WOLFSSL_NO_TLS12
13935
            ssl->options.minDowngrade = TLSv1_2_MINOR;
13936
            break;
13937
        #endif
13938
        case TLS1_3_VERSION:
13939
        #ifdef WOLFSSL_TLS13
13940
            ssl->options.minDowngrade = TLSv1_3_MINOR;
13941
            break;
13942
        #endif
13943
#endif
13944
#ifdef WOLFSSL_DTLS
13945
        case DTLS1_VERSION:
13946
    #ifndef NO_OLD_TLS
13947
            ssl->options.minDowngrade = DTLS_MINOR;
13948
            break;
13949
    #endif
13950
        case DTLS1_2_VERSION:
13951
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
13952
            break;
13953
#endif
13954
        default:
13955
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13956
            return WOLFSSL_FAILURE;
13957
    }
13958
13959
    switch (ver) {
13960
#ifndef NO_TLS
13961
    case TLS1_3_VERSION:
13962
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
13963
        FALL_THROUGH;
13964
    case TLS1_2_VERSION:
13965
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
13966
        FALL_THROUGH;
13967
    case TLS1_1_VERSION:
13968
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
13969
        FALL_THROUGH;
13970
    case TLS1_VERSION:
13971
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
13972
        break;
13973
    case SSL3_VERSION:
13974
    case SSL2_VERSION:
13975
        /* Nothing to do here */
13976
        break;
13977
#endif
13978
#ifdef WOLFSSL_DTLS
13979
    case DTLS1_VERSION:
13980
    case DTLS1_2_VERSION:
13981
        break;
13982
#endif
13983
    default:
13984
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
13985
        return WOLFSSL_FAILURE;
13986
    }
13987
13988
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
13989
}
13990
13991
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
13992
{
13993
    int i;
13994
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
13995
13996
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
13997
13998
    if (ssl == NULL) {
13999
        return WOLFSSL_FAILURE;
14000
    }
14001
    if (version != 0) {
14002
        return Set_SSL_min_proto_version(ssl, version);
14003
    }
14004
14005
    /* when 0 is specified as version, try to find out the min version */
14006
    for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
14007
        ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
14008
        if (ret == WOLFSSL_SUCCESS)
14009
            break;
14010
    }
14011
14012
    return ret;
14013
}
14014
14015
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
14016
{
14017
14018
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
14019
14020
    if (!ssl) {
14021
        WOLFSSL_MSG("Bad parameter");
14022
        return WOLFSSL_FAILURE;
14023
    }
14024
14025
    switch (ver) {
14026
    case SSL2_VERSION:
14027
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
14028
        return WOLFSSL_FAILURE;
14029
#ifndef NO_TLS
14030
    case SSL3_VERSION:
14031
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
14032
        FALL_THROUGH;
14033
    case TLS1_VERSION:
14034
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
14035
        FALL_THROUGH;
14036
    case TLS1_1_VERSION:
14037
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
14038
        FALL_THROUGH;
14039
    case TLS1_2_VERSION:
14040
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
14041
        FALL_THROUGH;
14042
    case TLS1_3_VERSION:
14043
        /* Nothing to do here */
14044
        break;
14045
#endif
14046
#ifdef WOLFSSL_DTLS
14047
    case DTLS1_VERSION:
14048
    case DTLS1_2_VERSION:
14049
        break;
14050
#endif
14051
    default:
14052
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
14053
        return WOLFSSL_FAILURE;
14054
    }
14055
14056
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
14057
}
14058
14059
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
14060
{
14061
    int i;
14062
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
14063
14064
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
14065
14066
    if (ssl == NULL) {
14067
        return WOLFSSL_FAILURE;
14068
    }
14069
    if (version != 0) {
14070
        return Set_SSL_max_proto_version(ssl, version);
14071
    }
14072
14073
    /* when 0 is specified as version, try to find out the min version from
14074
     * the bottom to top of the protoverTbl.
14075
     */
14076
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
14077
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
14078
        if (ret == WOLFSSL_SUCCESS)
14079
            break;
14080
    }
14081
14082
    return ret;
14083
}
14084
14085
static int GetMinProtoVersion(int minDowngrade)
14086
{
14087
    int ret;
14088
14089
    switch (minDowngrade) {
14090
#ifndef NO_OLD_TLS
14091
    #ifdef WOLFSSL_ALLOW_SSLV3
14092
        case SSLv3_MINOR:
14093
            ret = SSL3_VERSION;
14094
            break;
14095
    #endif
14096
    #ifdef WOLFSSL_ALLOW_TLSV10
14097
        case TLSv1_MINOR:
14098
            ret = TLS1_VERSION;
14099
            break;
14100
    #endif
14101
        case TLSv1_1_MINOR:
14102
            ret = TLS1_1_VERSION;
14103
            break;
14104
#endif
14105
#ifndef WOLFSSL_NO_TLS12
14106
        case TLSv1_2_MINOR:
14107
            ret = TLS1_2_VERSION;
14108
            break;
14109
#endif
14110
#ifdef WOLFSSL_TLS13
14111
        case TLSv1_3_MINOR:
14112
            ret = TLS1_3_VERSION;
14113
            break;
14114
#endif
14115
        default:
14116
            ret = 0;
14117
            break;
14118
    }
14119
14120
    return ret;
14121
}
14122
14123
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
14124
{
14125
    int ret = 0;
14126
14127
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
14128
14129
    if (ctx != NULL) {
14130
        if (ctx->minProto) {
14131
            ret = 0;
14132
        }
14133
        else {
14134
            ret = GetMinProtoVersion(ctx->minDowngrade);
14135
        }
14136
    }
14137
    else {
14138
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
14139
    }
14140
14141
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
14142
14143
    return ret;
14144
}
14145
14146
14147
/* returns the maximum allowed protocol version given the 'options' used
14148
 * returns WOLFSSL_FATAL_ERROR on no match */
14149
static int GetMaxProtoVersion(long options)
14150
{
14151
#ifndef NO_TLS
14152
#ifdef WOLFSSL_TLS13
14153
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
14154
        return TLS1_3_VERSION;
14155
#endif
14156
#ifndef WOLFSSL_NO_TLS12
14157
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
14158
        return TLS1_2_VERSION;
14159
#endif
14160
#ifndef NO_OLD_TLS
14161
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
14162
        return TLS1_1_VERSION;
14163
    #ifdef WOLFSSL_ALLOW_TLSV10
14164
    if (!(options & WOLFSSL_OP_NO_TLSv1))
14165
        return TLS1_VERSION;
14166
    #endif
14167
    #ifdef WOLFSSL_ALLOW_SSLV3
14168
    if (!(options & WOLFSSL_OP_NO_SSLv3))
14169
        return SSL3_VERSION;
14170
    #endif
14171
#endif
14172
#else
14173
    (void)options;
14174
#endif /* NO_TLS */
14175
    return WOLFSSL_FATAL_ERROR;
14176
}
14177
14178
14179
/* returns the maximum protocol version for 'ctx' */
14180
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
14181
{
14182
    int ret = 0;
14183
    long options = 0; /* default to nothing set */
14184
14185
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
14186
14187
    if (ctx != NULL) {
14188
        options = wolfSSL_CTX_get_options(ctx);
14189
    }
14190
14191
    if ((ctx != NULL) && ctx->maxProto) {
14192
        ret = 0;
14193
    }
14194
    else {
14195
        ret = GetMaxProtoVersion(options);
14196
    }
14197
14198
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
14199
14200
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
14201
        WOLFSSL_MSG("Error getting max proto version");
14202
        ret = 0; /* setting ret to 0 to match compat return */
14203
    }
14204
    return ret;
14205
}
14206
#endif /* OPENSSL_EXTRA */
14207
14208
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
14209
    defined(HAVE_SECRET_CALLBACK)
14210
#if !defined(NO_WOLFSSL_CLIENT)
14211
/* Return the amount of random bytes copied over or error case.
14212
 * ssl : ssl struct after handshake
14213
 * out : buffer to hold random bytes
14214
 * outSz : either 0 (return max buffer sz) or size of out buffer
14215
 */
14216
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
14217
                                                                   size_t outSz)
14218
{
14219
    size_t size;
14220
14221
    /* return max size of buffer */
14222
    if (outSz == 0) {
14223
        return RAN_LEN;
14224
    }
14225
14226
    if (ssl == NULL || out == NULL) {
14227
        return 0;
14228
    }
14229
14230
    if (ssl->arrays == NULL) {
14231
        WOLFSSL_MSG("Arrays struct not saved after handshake");
14232
        return 0;
14233
    }
14234
14235
    if (outSz > RAN_LEN) {
14236
        size = RAN_LEN;
14237
    }
14238
    else {
14239
        size = outSz;
14240
    }
14241
14242
    XMEMCPY(out, ssl->arrays->clientRandom, size);
14243
    return size;
14244
}
14245
#endif /* !NO_WOLFSSL_CLIENT */
14246
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
14247
14248
#ifdef OPENSSL_EXTRA
14249
14250
    unsigned long wolfSSLeay(void)
14251
    {
14252
#ifdef SSLEAY_VERSION_NUMBER
14253
        return SSLEAY_VERSION_NUMBER;
14254
#else
14255
        return OPENSSL_VERSION_NUMBER;
14256
#endif
14257
    }
14258
14259
    unsigned long wolfSSL_OpenSSL_version_num(void)
14260
    {
14261
        return OPENSSL_VERSION_NUMBER;
14262
    }
14263
14264
    const char* wolfSSLeay_version(int type)
14265
    {
14266
        (void)type;
14267
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
14268
        return wolfSSL_OpenSSL_version(type);
14269
#else
14270
        return wolfSSL_OpenSSL_version();
14271
#endif
14272
    }
14273
#endif /* OPENSSL_EXTRA */
14274
14275
#ifdef OPENSSL_EXTRA
14276
    void wolfSSL_ERR_free_strings(void)
14277
    {
14278
        /* handled internally */
14279
    }
14280
14281
    void wolfSSL_cleanup_all_ex_data(void)
14282
    {
14283
        /* nothing to do here */
14284
    }
14285
14286
#endif /* OPENSSL_EXTRA */
14287
14288
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
14289
    defined(HAVE_CURL)
14290
    void wolfSSL_ERR_clear_error(void)
14291
    {
14292
        WOLFSSL_ENTER("wolfSSL_ERR_clear_error");
14293
    #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
14294
        wc_ClearErrorNodes();
14295
    #endif
14296
    }
14297
#endif
14298
14299
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
14300
    int wolfSSL_clear(WOLFSSL* ssl)
14301
    {
14302
        WOLFSSL_ENTER("wolfSSL_clear");
14303
14304
        if (ssl == NULL) {
14305
            return WOLFSSL_FAILURE;
14306
        }
14307
14308
        if (!ssl->options.handShakeDone) {
14309
            /* Only reset the session if we didn't complete a handshake */
14310
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
14311
            ssl->session = wolfSSL_NewSession(ssl->heap);
14312
            if (ssl->session == NULL) {
14313
                return WOLFSSL_FAILURE;
14314
            }
14315
        }
14316
14317
        /* reset error */
14318
        ssl->error = 0;
14319
14320
        /* reset option bits */
14321
        ssl->options.isClosed = 0;
14322
        ssl->options.connReset = 0;
14323
        ssl->options.sentNotify = 0;
14324
        ssl->options.closeNotify = 0;
14325
        ssl->options.sendVerify = 0;
14326
        ssl->options.serverState = NULL_STATE;
14327
        ssl->options.clientState = NULL_STATE;
14328
        ssl->options.connectState = CONNECT_BEGIN;
14329
        ssl->options.acceptState  = ACCEPT_BEGIN;
14330
        ssl->options.handShakeState  = NULL_STATE;
14331
        ssl->options.handShakeDone = 0;
14332
        ssl->options.processReply = 0; /* doProcessInit */
14333
        ssl->options.havePeerVerify = 0;
14334
        ssl->options.havePeerCert = 0;
14335
        ssl->options.peerAuthGood = 0;
14336
        ssl->options.tls1_3 = 0;
14337
        ssl->options.haveSessionId = 0;
14338
        ssl->options.tls = 0;
14339
        ssl->options.tls1_1 = 0;
14340
    #ifdef WOLFSSL_TLS13
14341
    #ifdef WOLFSSL_SEND_HRR_COOKIE
14342
        ssl->options.hrrSentCookie = 0;
14343
    #endif
14344
        ssl->options.hrrSentKeyShare = 0;
14345
    #endif
14346
    #ifdef WOLFSSL_DTLS
14347
        ssl->options.dtlsStateful = 0;
14348
    #endif
14349
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
14350
        ssl->options.noPskDheKe = 0;
14351
      #ifdef HAVE_SUPPORTED_CURVES
14352
        ssl->options.onlyPskDheKe = 0;
14353
      #endif
14354
    #endif
14355
    #ifdef HAVE_SESSION_TICKET
14356
        #ifdef WOLFSSL_TLS13
14357
        ssl->options.ticketsSent = 0;
14358
        #endif
14359
        ssl->options.rejectTicket = 0;
14360
    #endif
14361
    #ifdef WOLFSSL_EARLY_DATA
14362
        ssl->earlyData = no_early_data;
14363
        ssl->earlyDataSz = 0;
14364
    #endif
14365
14366
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
14367
        TLSX_FreeAll(ssl->extensions, ssl->heap);
14368
        ssl->extensions = NULL;
14369
    #endif
14370
14371
        if (ssl->keys.encryptionOn) {
14372
            ForceZero(ssl->buffers.inputBuffer.buffer -
14373
                ssl->buffers.inputBuffer.offset,
14374
                ssl->buffers.inputBuffer.bufferSize);
14375
        #ifdef WOLFSSL_CHECK_MEM_ZERO
14376
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
14377
                ssl->buffers.inputBuffer.offset,
14378
                ssl->buffers.inputBuffer.bufferSize);
14379
        #endif
14380
        }
14381
        ssl->keys.encryptionOn = 0;
14382
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
14383
14384
        FreeCiphers(ssl);
14385
        InitCiphers(ssl);
14386
        InitCipherSpecs(&ssl->specs);
14387
14388
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
14389
            return WOLFSSL_FAILURE;
14390
14391
        if (InitHandshakeHashes(ssl) != 0)
14392
            return WOLFSSL_FAILURE;
14393
14394
#ifdef KEEP_PEER_CERT
14395
        FreeX509(&ssl->peerCert);
14396
        InitX509(&ssl->peerCert, 0, ssl->heap);
14397
#endif
14398
14399
#ifdef WOLFSSL_QUIC
14400
        wolfSSL_quic_clear(ssl);
14401
#endif
14402
#ifdef HAVE_OCSP
14403
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
14404
        ssl->response_idx = 0;
14405
#endif
14406
#endif
14407
        return WOLFSSL_SUCCESS;
14408
    }
14409
14410
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
14411
14412
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
14413
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
14414
    {
14415
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
14416
14417
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
14418
        switch(mode) {
14419
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
14420
                ctx->partialWrite = 1;
14421
                break;
14422
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
14423
            case SSL_MODE_RELEASE_BUFFERS:
14424
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
14425
                break;
14426
            #endif
14427
            case WOLFSSL_MODE_AUTO_RETRY:
14428
                ctx->autoRetry = 1;
14429
                break;
14430
            default:
14431
                WOLFSSL_MSG("Mode Not Implemented");
14432
        }
14433
14434
        /* WOLFSSL_MODE_AUTO_RETRY
14435
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
14436
14437
        return mode;
14438
    }
14439
14440
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
14441
    {
14442
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
14443
14444
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
14445
        switch(mode) {
14446
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
14447
                ctx->partialWrite = 0;
14448
                break;
14449
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
14450
            case SSL_MODE_RELEASE_BUFFERS:
14451
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
14452
                break;
14453
            #endif
14454
            case WOLFSSL_MODE_AUTO_RETRY:
14455
                ctx->autoRetry = 0;
14456
                break;
14457
            default:
14458
                WOLFSSL_MSG("Mode Not Implemented");
14459
        }
14460
14461
        /* WOLFSSL_MODE_AUTO_RETRY
14462
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
14463
14464
        return 0;
14465
    }
14466
#endif
14467
14468
#ifdef OPENSSL_EXTRA
14469
14470
    #ifndef NO_WOLFSSL_STUB
14471
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
14472
    {
14473
        /* TODO: */
14474
        (void)ssl;
14475
        WOLFSSL_STUB("SSL_get_mode");
14476
        return 0;
14477
    }
14478
    #endif
14479
14480
    #ifndef NO_WOLFSSL_STUB
14481
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
14482
    {
14483
        /* TODO: */
14484
        (void)ctx;
14485
        WOLFSSL_STUB("SSL_CTX_get_mode");
14486
        return 0;
14487
    }
14488
    #endif
14489
14490
    #ifndef NO_WOLFSSL_STUB
14491
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
14492
    {
14493
        /* TODO: maybe? */
14494
        (void)ctx;
14495
        (void)m;
14496
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
14497
    }
14498
    #endif
14499
14500
14501
    /* returns the unsigned error value and increments the pointer into the
14502
     * error queue.
14503
     *
14504
     * file  pointer to file name
14505
     * line  gets set to line number of error when not NULL
14506
     */
14507
    unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line)
14508
    {
14509
    #ifdef WOLFSSL_HAVE_ERROR_QUEUE
14510
        int ret = wc_PullErrorNode(file, NULL, line);
14511
        if (ret < 0) {
14512
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
14513
                return 0; /* no errors in queue */
14514
            WOLFSSL_MSG("Issue getting error node");
14515
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret);
14516
            ret = 0 - ret; /* return absolute value of error */
14517
14518
            /* panic and try to clear out nodes */
14519
            wc_ClearErrorNodes();
14520
        }
14521
        return (unsigned long)ret;
14522
    #else
14523
        (void)file;
14524
        (void)line;
14525
14526
        return 0;
14527
    #endif
14528
    }
14529
14530
14531
#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \
14532
    (!defined(_WIN32) && !defined(NO_ERROR_QUEUE))
14533
    static const char WOLFSSL_SYS_ACCEPT_T[]  = "accept";
14534
    static const char WOLFSSL_SYS_BIND_T[]    = "bind";
14535
    static const char WOLFSSL_SYS_CONNECT_T[] = "connect";
14536
    static const char WOLFSSL_SYS_FOPEN_T[]   = "fopen";
14537
    static const char WOLFSSL_SYS_FREAD_T[]   = "fread";
14538
    static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo";
14539
    static const char WOLFSSL_SYS_GETSOCKOPT_T[]  = "getsockopt";
14540
    static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname";
14541
    static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname";
14542
    static const char WOLFSSL_SYS_GETNAMEINFO_T[]   = "getnameinfo";
14543
    static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname";
14544
    static const char WOLFSSL_SYS_IOCTLSOCKET_T[]   = "ioctlsocket";
14545
    static const char WOLFSSL_SYS_LISTEN_T[]        = "listen";
14546
    static const char WOLFSSL_SYS_OPENDIR_T[]       = "opendir";
14547
    static const char WOLFSSL_SYS_SETSOCKOPT_T[]    = "setsockopt";
14548
    static const char WOLFSSL_SYS_SOCKET_T[]        = "socket";
14549
14550
    /* switch with int mapped to function name for compatibility */
14551
    static const char* wolfSSL_ERR_sys_func(int fun)
14552
    {
14553
        switch (fun) {
14554
            case WOLFSSL_SYS_ACCEPT:      return WOLFSSL_SYS_ACCEPT_T;
14555
            case WOLFSSL_SYS_BIND:        return WOLFSSL_SYS_BIND_T;
14556
            case WOLFSSL_SYS_CONNECT:     return WOLFSSL_SYS_CONNECT_T;
14557
            case WOLFSSL_SYS_FOPEN:       return WOLFSSL_SYS_FOPEN_T;
14558
            case WOLFSSL_SYS_FREAD:       return WOLFSSL_SYS_FREAD_T;
14559
            case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T;
14560
            case WOLFSSL_SYS_GETSOCKOPT:  return WOLFSSL_SYS_GETSOCKOPT_T;
14561
            case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T;
14562
            case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T;
14563
            case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T;
14564
            case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T;
14565
            case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T;
14566
            case WOLFSSL_SYS_LISTEN:      return WOLFSSL_SYS_LISTEN_T;
14567
            case WOLFSSL_SYS_OPENDIR:     return WOLFSSL_SYS_OPENDIR_T;
14568
            case WOLFSSL_SYS_SETSOCKOPT:  return WOLFSSL_SYS_SETSOCKOPT_T;
14569
            case WOLFSSL_SYS_SOCKET:      return WOLFSSL_SYS_SOCKET_T;
14570
            default:
14571
                return "NULL";
14572
        }
14573
    }
14574
#endif /* DEBUG_WOLFSSL */
14575
14576
14577
    void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file,
14578
            int line)
14579
    {
14580
        WOLFSSL_ENTER("wolfSSL_ERR_put_error");
14581
14582
        #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA)
14583
        (void)fun;
14584
        (void)err;
14585
        (void)file;
14586
        (void)line;
14587
        WOLFSSL_MSG("Not compiled in debug mode");
14588
        #elif defined(OPENSSL_EXTRA) && \
14589
                (defined(_WIN32) || defined(NO_ERROR_QUEUE))
14590
        (void)fun;
14591
        (void)file;
14592
        (void)line;
14593
        WOLFSSL_ERROR(err);
14594
        #else
14595
        WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line,
14596
            file, NULL);
14597
        #endif
14598
        (void)lib;
14599
    }
14600
14601
14602
    /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for
14603
     * more flexibility.
14604
     *
14605
     * file  output pointer to file where error happened
14606
     * line  output to line number of error
14607
     * data  output data. Is a string if WOLFSSL_ERR_TXT_STRING flag is used
14608
     * flags output format of output
14609
     *
14610
     * Returns the error value or 0 if no errors are in the queue
14611
     */
14612
    unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line,
14613
                                                  const char** data, int *flags)
14614
    {
14615
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
14616
        int ret;
14617
14618
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
14619
14620
        if (flags != NULL)
14621
            *flags = WOLFSSL_ERR_TXT_STRING; /* Clear the flags */
14622
14623
        ret = wc_PullErrorNode(file, data, line);
14624
        if (ret < 0) {
14625
            if (ret == WC_NO_ERR_TRACE(BAD_STATE_E))
14626
                return 0; /* no errors in queue */
14627
            WOLFSSL_MSG("Error with pulling error node!");
14628
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret);
14629
            ret = 0 - ret; /* return absolute value of error */
14630
14631
            /* panic and try to clear out nodes */
14632
            wc_ClearErrorNodes();
14633
        }
14634
14635
        return (unsigned long)ret;
14636
#else
14637
        WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data");
14638
        WOLFSSL_MSG("Error queue turned off, can not get error line");
14639
        (void)file;
14640
        (void)line;
14641
        (void)data;
14642
        (void)flags;
14643
        return 0;
14644
#endif
14645
    }
14646
14647
#endif /* OPENSSL_EXTRA */
14648
14649
14650
#if (defined(KEEP_PEER_CERT) && defined(SESSION_CERTS)) || \
14651
    (defined(OPENSSL_EXTRA) && defined(SESSION_CERTS))
14652
    /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object.
14653
     *
14654
     * x509  WOLFSSL_X509 object to decode into.
14655
     * in    X509 DER data.
14656
     * len   Length of the X509 DER data.
14657
     * returns the new certificate on success, otherwise NULL.
14658
     */
14659
    static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len)
14660
    {
14661
        int          ret;
14662
        WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
14663
        if (x509 == NULL || in == NULL || len <= 0)
14664
            return BAD_FUNC_ARG;
14665
14666
        WC_ALLOC_VAR_EX(cert, DecodedCert, 1, NULL, DYNAMIC_TYPE_DCERT,
14667
            return MEMORY_E);
14668
14669
        /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object.
14670
         */
14671
        InitDecodedCert(cert, (byte*)in, (word32)len, NULL);
14672
        if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) == 0) {
14673
        /* Check if x509 was not previously initialized by wolfSSL_X509_new() */
14674
            if (x509->dynamicMemory != TRUE)
14675
                InitX509(x509, 0, NULL);
14676
            ret = CopyDecodedToX509(x509, cert);
14677
        }
14678
        FreeDecodedCert(cert);
14679
        WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
14680
14681
        return ret;
14682
    }
14683
#endif /* (KEEP_PEER_CERT & SESSION_CERTS) || (OPENSSL_EXTRA & SESSION_CERTS) */
14684
14685
14686
#ifdef KEEP_PEER_CERT
14687
    WOLFSSL_ABI
14688
    WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl)
14689
    {
14690
        WOLFSSL_X509* ret = NULL;
14691
        WOLFSSL_ENTER("wolfSSL_get_peer_certificate");
14692
        if (ssl != NULL) {
14693
            if (ssl->peerCert.issuer.sz)
14694
                ret = wolfSSL_X509_dup(&ssl->peerCert);
14695
#ifdef SESSION_CERTS
14696
            else if (ssl->session->chain.count > 0) {
14697
                if (DecodeToX509(&ssl->peerCert,
14698
                        ssl->session->chain.certs[0].buffer,
14699
                        ssl->session->chain.certs[0].length) == 0) {
14700
                    ret = wolfSSL_X509_dup(&ssl->peerCert);
14701
                }
14702
            }
14703
#endif
14704
        }
14705
        WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL);
14706
        return ret;
14707
    }
14708
14709
#endif /* KEEP_PEER_CERT */
14710
14711
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
14712
/* Return stack of peer certs.
14713
 * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl
14714
 * is.
14715
 */
14716
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl)
14717
{
14718
    WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain");
14719
14720
    if (ssl == NULL)
14721
        return NULL;
14722
14723
    /* Try to populate if NULL or empty */
14724
    if (ssl->peerCertChain == NULL ||
14725
            wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) {
14726
        wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl);
14727
    }
14728
    return ssl->peerCertChain;
14729
}
14730
14731
14732
static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
14733
        WOLFSSL_X509 *x);
14734
/**
14735
 * Recursively push the issuer CA chain onto the stack
14736
 * @param cm The cert manager that is queried for the issuer
14737
 * @param x  This cert's issuer will be queried in cm
14738
 * @param sk The issuer is pushed onto this stack
14739
 * @return 0 on success or no issuer found
14740
 *         WOLFSSL_FATAL_ERROR on a fatal error
14741
 */
14742
static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm,
14743
        WOLFSSL_X509 *x, WOLFSSL_STACK* sk)
14744
{
14745
    int i;
14746
    for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
14747
        WOLFSSL_X509* issuer = NULL;
14748
        if (x509GetIssuerFromCM(&issuer, cm, x) != WOLFSSL_SUCCESS)
14749
            break;
14750
        if (wolfSSL_sk_X509_push(sk, issuer) <= 0) {
14751
            wolfSSL_X509_free(issuer);
14752
            issuer = NULL;
14753
            return WOLFSSL_FATAL_ERROR;
14754
        }
14755
        x = issuer;
14756
    }
14757
    return 0;
14758
}
14759
14760
14761
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
14762
    or ssl->verifiedChain based off of the ssl session chain. Attempts to place
14763
    CA certificates at the bottom of the stack for a verified chain. Returns
14764
    stack of WOLFSSL_X509 certs or NULL on failure */
14765
static WOLF_STACK_OF(WOLFSSL_X509)* CreatePeerCertChain(const WOLFSSL* ssl,
14766
    int verifiedFlag)
14767
{
14768
    WOLFSSL_STACK* sk;
14769
    WOLFSSL_X509* x509;
14770
    int i = 0;
14771
    int err;
14772
14773
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
14774
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
14775
        return NULL;
14776
14777
    sk = wolfSSL_sk_X509_new_null();
14778
    for (i = 0; i < ssl->session->chain.count; i++) {
14779
        x509 = wolfSSL_X509_new_ex(ssl->heap);
14780
        if (x509 == NULL) {
14781
            WOLFSSL_MSG("Error Creating X509");
14782
            wolfSSL_sk_X509_pop_free(sk, NULL);
14783
            return NULL;
14784
        }
14785
        err = DecodeToX509(x509, ssl->session->chain.certs[i].buffer,
14786
                             ssl->session->chain.certs[i].length);
14787
        if (err == 0 && wolfSSL_sk_X509_push(sk, x509) <= 0)
14788
            err = WOLFSSL_FATAL_ERROR;
14789
        if (err == 0 && i == ssl->session->chain.count-1 && verifiedFlag) {
14790
            /* On the last element in the verified chain try to add the CA chain
14791
             * if we have one for this cert */
14792
            SSL_CM_WARNING(ssl);
14793
            err = PushCAx509Chain(SSL_CM(ssl), x509, sk);
14794
        }
14795
        if (err != 0) {
14796
            WOLFSSL_MSG("Error decoding cert");
14797
            wolfSSL_X509_free(x509);
14798
            x509 = NULL;
14799
            wolfSSL_sk_X509_pop_free(sk, NULL);
14800
            return NULL;
14801
        }
14802
    }
14803
14804
    if (sk == NULL) {
14805
        WOLFSSL_MSG("Null session chain");
14806
    }
14807
    return sk;
14808
}
14809
14810
14811
/* Builds up and creates a stack of peer certificates for ssl->peerCertChain
14812
    returns the stack on success and NULL on failure */
14813
WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl)
14814
{
14815
    WOLFSSL_STACK* sk;
14816
14817
    WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain");
14818
    if ((ssl == NULL) || (ssl->session->chain.count == 0))
14819
        return NULL;
14820
14821
    sk = CreatePeerCertChain(ssl, 0);
14822
14823
    if (sk != NULL) {
14824
        if (ssl->options.side == WOLFSSL_SERVER_END) {
14825
            if (ssl->session->peer)
14826
                wolfSSL_X509_free(ssl->session->peer);
14827
14828
            ssl->session->peer = wolfSSL_sk_X509_shift(sk);
14829
            ssl->session->peerVerifyRet = ssl->peerVerifyRet;
14830
        }
14831
        if (ssl->peerCertChain != NULL)
14832
            wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
14833
        /* This is Free'd when ssl is Free'd */
14834
        ssl->peerCertChain = sk;
14835
    }
14836
    return sk;
14837
}
14838
14839
#ifdef KEEP_PEER_CERT
14840
/**
14841
 * Implemented in a similar way that ngx_ssl_ocsp_validate does it when
14842
 * SSL_get0_verified_chain is not available.
14843
 * @param ssl WOLFSSL object to extract certs from
14844
 * @return Stack of verified certs
14845
 */
14846
WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl)
14847
{
14848
    WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL;
14849
    WOLFSSL_X509_STORE_CTX* storeCtx = NULL;
14850
    WOLFSSL_X509* peerCert = NULL;
14851
14852
    WOLFSSL_ENTER("wolfSSL_get0_verified_chain");
14853
14854
    if (ssl == NULL || ssl->ctx == NULL) {
14855
        WOLFSSL_MSG("Bad parameter");
14856
        return NULL;
14857
    }
14858
14859
    peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl);
14860
    if (peerCert == NULL) {
14861
        WOLFSSL_MSG("wolfSSL_get_peer_certificate error");
14862
        return NULL;
14863
    }
14864
    /* wolfSSL_get_peer_certificate returns a copy. We want the internal
14865
     * member so that we don't have to worry about free'ing it. We call
14866
     * wolfSSL_get_peer_certificate so that we don't have to worry about
14867
     * setting up the internal pointer. */
14868
    wolfSSL_X509_free(peerCert);
14869
    peerCert = (WOLFSSL_X509*)&ssl->peerCert;
14870
    chain = CreatePeerCertChain((WOLFSSL*)ssl, 1);
14871
    if (chain == NULL) {
14872
        WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error");
14873
        return NULL;
14874
    }
14875
14876
    if (ssl->verifiedChain != NULL) {
14877
        wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL);
14878
    }
14879
    ((WOLFSSL*)ssl)->verifiedChain = chain;
14880
14881
    storeCtx = wolfSSL_X509_STORE_CTX_new();
14882
    if (storeCtx == NULL) {
14883
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error");
14884
        return NULL;
14885
    }
14886
    if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl),
14887
            peerCert, chain) != WOLFSSL_SUCCESS) {
14888
        WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error");
14889
        wolfSSL_X509_STORE_CTX_free(storeCtx);
14890
        return NULL;
14891
    }
14892
    if (wolfSSL_X509_verify_cert(storeCtx) <= 0) {
14893
        WOLFSSL_MSG("wolfSSL_X509_verify_cert error");
14894
        wolfSSL_X509_STORE_CTX_free(storeCtx);
14895
        return NULL;
14896
    }
14897
    wolfSSL_X509_STORE_CTX_free(storeCtx);
14898
    return chain;
14899
}
14900
#endif /* KEEP_PEER_CERT */
14901
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
14902
14903
#ifndef NO_CERTS
14904
14905
/* OPENSSL_EXTRA is needed for wolfSSL_X509_d21 function
14906
   KEEP_OUR_CERT is to insure ability for returning ssl certificate */
14907
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
14908
    defined(KEEP_OUR_CERT)
14909
WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl)
14910
{
14911
    if (ssl == NULL) {
14912
        return NULL;
14913
    }
14914
14915
    if (ssl->buffers.weOwnCert) {
14916
        if (ssl->ourCert == NULL) {
14917
            if (ssl->buffers.certificate == NULL) {
14918
                WOLFSSL_MSG("Certificate buffer not set!");
14919
                return NULL;
14920
            }
14921
            #ifndef WOLFSSL_X509_STORE_CERTS
14922
            ssl->ourCert = wolfSSL_X509_d2i_ex(NULL,
14923
                                         ssl->buffers.certificate->buffer,
14924
                                         (int)ssl->buffers.certificate->length,
14925
                                         ssl->heap);
14926
            #endif
14927
        }
14928
        return ssl->ourCert;
14929
    }
14930
    else { /* if cert not owned get parent ctx cert or return null */
14931
        if (ssl->ctx) {
14932
            if (ssl->ctx->ourCert == NULL) {
14933
                if (ssl->ctx->certificate == NULL) {
14934
                    WOLFSSL_MSG("Ctx Certificate buffer not set!");
14935
                    return NULL;
14936
                }
14937
                #ifndef WOLFSSL_X509_STORE_CERTS
14938
                ssl->ctx->ourCert = wolfSSL_X509_d2i_ex(NULL,
14939
                                          ssl->ctx->certificate->buffer,
14940
                                          (int)ssl->ctx->certificate->length,
14941
                                          ssl->heap);
14942
                #endif
14943
                ssl->ctx->ownOurCert = 1;
14944
            }
14945
            return ssl->ctx->ourCert;
14946
        }
14947
    }
14948
14949
    return NULL;
14950
}
14951
14952
WOLFSSL_X509* wolfSSL_CTX_get0_certificate(WOLFSSL_CTX* ctx)
14953
{
14954
    if (ctx) {
14955
        if (ctx->ourCert == NULL) {
14956
            if (ctx->certificate == NULL) {
14957
                WOLFSSL_MSG("Ctx Certificate buffer not set!");
14958
                return NULL;
14959
            }
14960
            #ifndef WOLFSSL_X509_STORE_CERTS
14961
            ctx->ourCert = wolfSSL_X509_d2i_ex(NULL,
14962
                                           ctx->certificate->buffer,
14963
                                           (int)ctx->certificate->length,
14964
                                           ctx->heap);
14965
            #endif
14966
            ctx->ownOurCert = 1;
14967
        }
14968
        return ctx->ourCert;
14969
    }
14970
    return NULL;
14971
}
14972
#endif /* OPENSSL_EXTRA && KEEP_OUR_CERT */
14973
#endif /* NO_CERTS */
14974
14975
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
14976
void wolfSSL_set_connect_state(WOLFSSL* ssl)
14977
{
14978
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
14979
    if (ssl == NULL) {
14980
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
14981
        return;
14982
    }
14983
14984
    #ifndef NO_DH
14985
    /* client creates its own DH parameters on handshake */
14986
    if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
14987
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
14988
            DYNAMIC_TYPE_PUBLIC_KEY);
14989
    }
14990
    ssl->buffers.serverDH_P.buffer = NULL;
14991
    if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
14992
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
14993
            DYNAMIC_TYPE_PUBLIC_KEY);
14994
    }
14995
    ssl->buffers.serverDH_G.buffer = NULL;
14996
    #endif
14997
14998
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
14999
        WOLFSSL_MSG("Error initializing client side");
15000
    }
15001
}
15002
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
15003
15004
15005
int wolfSSL_get_shutdown(const WOLFSSL* ssl)
15006
0
{
15007
0
    int isShutdown = 0;
15008
15009
0
    WOLFSSL_ENTER("wolfSSL_get_shutdown");
15010
15011
0
    if (ssl) {
15012
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
15013
        if (ssl->options.shutdownDone) {
15014
            /* The SSL object was possibly cleared with wolfSSL_clear after
15015
             * a successful shutdown. Simulate a response for a full
15016
             * bidirectional shutdown. */
15017
            isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN;
15018
        }
15019
        else
15020
#endif
15021
0
        {
15022
            /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent   *
15023
             * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */
15024
0
            if (ssl->options.sentNotify)
15025
0
                isShutdown |= WOLFSSL_SENT_SHUTDOWN;
15026
0
            if (ssl->options.closeNotify||ssl->options.connReset)
15027
0
                isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN;
15028
0
        }
15029
15030
0
    }
15031
15032
0
    WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown);
15033
0
    return isShutdown;
15034
0
}
15035
15036
15037
int wolfSSL_session_reused(WOLFSSL* ssl)
15038
0
{
15039
0
    int resuming = 0;
15040
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
15041
0
    if (ssl) {
15042
0
#ifndef HAVE_SECURE_RENEGOTIATION
15043
0
        resuming = ssl->options.resuming;
15044
#else
15045
        resuming = ssl->options.resuming || ssl->options.resumed;
15046
#endif
15047
0
    }
15048
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
15049
0
    return resuming;
15050
0
}
15051
15052
/* helper function that takes in a protocol version struct and returns string */
15053
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
15054
0
{
15055
0
    WOLFSSL_ENTER("wolfSSL_get_version");
15056
15057
0
    if (version == NULL) {
15058
0
        return "Bad arg";
15059
0
    }
15060
15061
0
    if (version->major == SSLv3_MAJOR) {
15062
0
        switch (version->minor) {
15063
0
            case SSLv3_MINOR :
15064
0
                return "SSLv3";
15065
0
            case TLSv1_MINOR :
15066
0
                return "TLSv1";
15067
0
            case TLSv1_1_MINOR :
15068
0
                return "TLSv1.1";
15069
0
            case TLSv1_2_MINOR :
15070
0
                return "TLSv1.2";
15071
0
            case TLSv1_3_MINOR :
15072
0
                return "TLSv1.3";
15073
0
            default:
15074
0
                return "unknown";
15075
0
        }
15076
0
    }
15077
#ifdef WOLFSSL_DTLS
15078
    else if (version->major == DTLS_MAJOR) {
15079
        switch (version->minor) {
15080
            case DTLS_MINOR :
15081
                return "DTLS";
15082
            case DTLSv1_2_MINOR :
15083
                return "DTLSv1.2";
15084
            case DTLSv1_3_MINOR :
15085
                return "DTLSv1.3";
15086
            default:
15087
                return "unknown";
15088
        }
15089
    }
15090
#endif /* WOLFSSL_DTLS */
15091
0
    return "unknown";
15092
0
}
15093
15094
15095
const char* wolfSSL_get_version(const WOLFSSL* ssl)
15096
0
{
15097
0
    if (ssl == NULL) {
15098
0
        WOLFSSL_MSG("Bad argument");
15099
0
        return "unknown";
15100
0
    }
15101
15102
0
    return wolfSSL_internal_get_version(&ssl->version);
15103
0
}
15104
15105
15106
/* current library version */
15107
const char* wolfSSL_lib_version(void)
15108
0
{
15109
0
    return LIBWOLFSSL_VERSION_STRING;
15110
0
}
15111
15112
#ifdef OPENSSL_EXTRA
15113
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
15114
const char* wolfSSL_OpenSSL_version(int a)
15115
{
15116
    (void)a;
15117
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
15118
}
15119
#else
15120
const char* wolfSSL_OpenSSL_version(void)
15121
{
15122
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
15123
}
15124
#endif /* WOLFSSL_QT */
15125
#endif
15126
15127
15128
/* current library version in hex */
15129
word32 wolfSSL_lib_version_hex(void)
15130
0
{
15131
0
    return LIBWOLFSSL_VERSION_HEX;
15132
0
}
15133
15134
15135
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
15136
0
{
15137
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
15138
0
    if (ssl)
15139
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
15140
0
    return 0;
15141
0
}
15142
15143
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
15144
0
{
15145
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
15146
0
    if (ssl) {
15147
0
        ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
15148
0
        ssl->cipher.cipherSuite  = ssl->options.cipherSuite;
15149
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
15150
        ssl->cipher.bits = ssl->specs.key_size * 8;
15151
#endif
15152
0
        return &ssl->cipher;
15153
0
    }
15154
0
    else
15155
0
        return NULL;
15156
0
}
15157
15158
15159
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
15160
0
{
15161
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
15162
15163
0
    if (cipher == NULL) {
15164
0
        return NULL;
15165
0
    }
15166
15167
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
15168
0
        !defined(WOLFSSL_QT)
15169
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
15170
    #else
15171
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
15172
                cipher->cipherSuite);
15173
    #endif
15174
0
}
15175
15176
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
15177
0
{
15178
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
15179
15180
0
    if (cipher == NULL || cipher->ssl == NULL) {
15181
0
        return NULL;
15182
0
    }
15183
15184
0
    return wolfSSL_get_version(cipher->ssl);
15185
0
}
15186
15187
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
15188
0
{
15189
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
15190
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
15191
0
}
15192
15193
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
15194
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
15195
0
{
15196
    /* get access to cipher_name_idx in internal.c */
15197
0
    return wolfSSL_get_cipher_name_internal(ssl);
15198
0
}
15199
15200
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
15201
    byte cipherSuite)
15202
0
{
15203
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
15204
0
}
15205
15206
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
15207
        byte cipherSuite)
15208
0
{
15209
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
15210
0
}
15211
15212
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
15213
0
                                       byte* cipherSuite, int *flags) {
15214
0
    if ((name == NULL) ||
15215
0
        (cipherSuite0 == NULL) ||
15216
0
        (cipherSuite == NULL) ||
15217
0
        (flags == NULL))
15218
0
        return BAD_FUNC_ARG;
15219
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
15220
0
                                  flags);
15221
0
}
15222
15223
15224
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
15225
0
{
15226
0
    word16 cipher_id = 0;
15227
15228
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
15229
15230
0
    if (cipher && cipher->ssl) {
15231
0
        cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) |
15232
0
                     cipher->ssl->options.cipherSuite;
15233
0
    }
15234
15235
0
    return cipher_id;
15236
0
}
15237
15238
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
15239
0
{
15240
0
    const WOLFSSL_CIPHER* cipher = NULL;
15241
0
    byte cipherSuite0, cipherSuite;
15242
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
15243
15244
    /* extract cipher id information */
15245
0
    cipherSuite =   (value       & 0xFF);
15246
0
    cipherSuite0 = ((value >> 8) & 0xFF);
15247
15248
    /* TODO: lookup by cipherSuite0 / cipherSuite */
15249
0
    (void)cipherSuite0;
15250
0
    (void)cipherSuite;
15251
15252
0
    return cipher;
15253
0
}
15254
15255
15256
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
15257
                                                                 !defined(NO_DH)
15258
#ifdef HAVE_FFDHE
15259
static const char* wolfssl_ffdhe_name(word16 group)
15260
0
{
15261
0
    const char* str = NULL;
15262
0
    switch (group) {
15263
0
        case WOLFSSL_FFDHE_2048:
15264
0
            str = "FFDHE_2048";
15265
0
            break;
15266
0
        case WOLFSSL_FFDHE_3072:
15267
0
            str = "FFDHE_3072";
15268
0
            break;
15269
0
        case WOLFSSL_FFDHE_4096:
15270
0
            str = "FFDHE_4096";
15271
0
            break;
15272
0
        case WOLFSSL_FFDHE_6144:
15273
0
            str = "FFDHE_6144";
15274
0
            break;
15275
0
        case WOLFSSL_FFDHE_8192:
15276
0
            str = "FFDHE_8192";
15277
0
            break;
15278
0
        default:
15279
0
            break;
15280
0
    }
15281
0
    return str;
15282
0
}
15283
#endif
15284
/* Return the name of the curve used for key exchange as a printable string.
15285
 *
15286
 * ssl  The SSL/TLS object.
15287
 * returns NULL if ECDH was not used, otherwise the name as a string.
15288
 */
15289
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
15290
0
{
15291
0
    const char* cName = NULL;
15292
15293
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
15294
15295
0
    if (ssl == NULL)
15296
0
        return NULL;
15297
15298
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
15299
    /* Check for post-quantum groups. Return now because we do not want the ECC
15300
     * check to override this result in the case of a hybrid. */
15301
    if (IsAtLeastTLSv1_3(ssl->version)) {
15302
        switch (ssl->namedGroup) {
15303
#ifndef WOLFSSL_NO_ML_KEM
15304
#if defined(WOLFSSL_WC_MLKEM)
15305
    #ifndef WOLFSSL_NO_ML_KEM_512
15306
        case WOLFSSL_ML_KEM_512:
15307
            return "ML_KEM_512";
15308
        case WOLFSSL_SECP256R1MLKEM512:
15309
            return "SecP256r1MLKEM512";
15310
#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
15311
        case WOLFSSL_P256_ML_KEM_512_OLD:
15312
            return "P256_ML_KEM_512_OLD";
15313
#endif
15314
        #ifdef HAVE_CURVE25519
15315
        case WOLFSSL_X25519MLKEM512:
15316
            return "X25519MLKEM512";
15317
        #endif
15318
    #endif
15319
    #ifndef WOLFSSL_NO_ML_KEM_768
15320
        case WOLFSSL_ML_KEM_768:
15321
            return "ML_KEM_768";
15322
        case WOLFSSL_SECP384R1MLKEM768:
15323
            return "SecP384r1MLKEM768";
15324
#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
15325
        case WOLFSSL_P384_ML_KEM_768_OLD:
15326
            return "P384_ML_KEM_768_OLD";
15327
#endif
15328
        case WOLFSSL_SECP256R1MLKEM768:
15329
            return "SecP256r1MLKEM768";
15330
        #ifdef HAVE_CURVE25519
15331
        case WOLFSSL_X25519MLKEM768:
15332
            return "X25519MLKEM768";
15333
        #endif
15334
        #ifdef HAVE_CURVE448
15335
        case WOLFSSL_X448MLKEM768:
15336
            return "X448MLKEM768";
15337
        #endif
15338
    #endif
15339
    #ifndef WOLFSSL_NO_ML_KEM_1024
15340
        case WOLFSSL_ML_KEM_1024:
15341
            return "ML_KEM_1024";
15342
        case WOLFSSL_SECP521R1MLKEM1024:
15343
            return "SecP521r1MLKEM1024";
15344
#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
15345
        case WOLFSSL_P521_ML_KEM_1024_OLD:
15346
            return "P521_ML_KEM_1024_OLD";
15347
#endif
15348
        case WOLFSSL_SECP384R1MLKEM1024:
15349
            return "SecP384r1MLKEM1024";
15350
    #endif
15351
#elif defined(HAVE_LIBOQS)
15352
        case WOLFSSL_ML_KEM_512:
15353
            return "ML_KEM_512";
15354
        case WOLFSSL_ML_KEM_768:
15355
            return "ML_KEM_768";
15356
        case WOLFSSL_ML_KEM_1024:
15357
            return "ML_KEM_1024";
15358
        case WOLFSSL_SECP256R1MLKEM512:
15359
            return "SecP256r1MLKEM512";
15360
        case WOLFSSL_SECP384R1MLKEM768:
15361
            return "SecP384r1MLKEM768";
15362
        case WOLFSSL_SECP256R1MLKEM768:
15363
            return "SecP256r1MLKEM768";
15364
        case WOLFSSL_SECP521R1MLKEM1024:
15365
            return "SecP521r1MLKEM1024";
15366
        case WOLFSSL_SECP384R1MLKEM1024:
15367
            return "SecP384r1MLKEM1024";
15368
    #ifdef HAVE_CURVE25519
15369
        case WOLFSSL_X25519MLKEM512:
15370
            return "X25519MLKEM512";
15371
        case WOLFSSL_X25519MLKEM768:
15372
            return "X25519MLKEM768";
15373
    #endif
15374
    #ifdef HAVE_CURVE448
15375
        case WOLFSSL_X448MLKEM768:
15376
            return "X448MLKEM768";
15377
    #endif
15378
#endif /* WOLFSSL_WC_MLKEM */
15379
#endif /* WOLFSSL_NO_ML_KEM */
15380
#ifdef WOLFSSL_MLKEM_KYBER
15381
#if defined(WOLFSSL_WC_MLKEM)
15382
    #ifndef WOLFSSL_NO_KYBER512
15383
        case WOLFSSL_KYBER_LEVEL1:
15384
            return "KYBER_LEVEL1";
15385
        case WOLFSSL_P256_KYBER_LEVEL1:
15386
            return "P256_KYBER_LEVEL1";
15387
        #ifdef HAVE_CURVE25519
15388
        case WOLFSSL_X25519_KYBER_LEVEL1:
15389
            return "X25519_KYBER_LEVEL1";
15390
        #endif
15391
    #endif
15392
    #ifndef WOLFSSL_NO_KYBER768
15393
        case WOLFSSL_KYBER_LEVEL3:
15394
            return "KYBER_LEVEL3";
15395
        case WOLFSSL_P384_KYBER_LEVEL3:
15396
            return "P384_KYBER_LEVEL3";
15397
        case WOLFSSL_P256_KYBER_LEVEL3:
15398
            return "P256_KYBER_LEVEL3";
15399
        #ifdef HAVE_CURVE25519
15400
        case WOLFSSL_X25519_KYBER_LEVEL3:
15401
            return "X25519_KYBER_LEVEL3";
15402
        #endif
15403
        #ifdef HAVE_CURVE448
15404
        case WOLFSSL_X448_KYBER_LEVEL3:
15405
            return "X448_KYBER_LEVEL3";
15406
        #endif
15407
    #endif
15408
    #ifndef WOLFSSL_NO_KYBER1024
15409
        case WOLFSSL_KYBER_LEVEL5:
15410
            return "KYBER_LEVEL5";
15411
        case WOLFSSL_P521_KYBER_LEVEL5:
15412
            return "P521_KYBER_LEVEL5";
15413
    #endif
15414
#elif defined (HAVE_LIBOQS)
15415
        case WOLFSSL_KYBER_LEVEL1:
15416
            return "KYBER_LEVEL1";
15417
        case WOLFSSL_KYBER_LEVEL3:
15418
            return "KYBER_LEVEL3";
15419
        case WOLFSSL_KYBER_LEVEL5:
15420
            return "KYBER_LEVEL5";
15421
        case WOLFSSL_P256_KYBER_LEVEL1:
15422
            return "P256_KYBER_LEVEL1";
15423
        case WOLFSSL_P384_KYBER_LEVEL3:
15424
            return "P384_KYBER_LEVEL3";
15425
        case WOLFSSL_P256_KYBER_LEVEL3:
15426
            return "P256_KYBER_LEVEL3";
15427
        case WOLFSSL_P521_KYBER_LEVEL5:
15428
            return "P521_KYBER_LEVEL5";
15429
    #ifdef HAVE_CURVE25519
15430
        case WOLFSSL_X25519_KYBER_LEVEL1:
15431
            return "X25519_KYBER_LEVEL1";
15432
        case WOLFSSL_X25519_KYBER_LEVEL3:
15433
            return "X25519_KYBER_LEVEL3";
15434
    #endif
15435
    #ifdef HAVE_CURVE448
15436
        case WOLFSSL_X448_KYBER_LEVEL3:
15437
            return "X448_KYBER_LEVEL3";
15438
    #endif
15439
#endif /* WOLFSSL_WC_MLKEM */
15440
#endif /* WOLFSSL_MLKEM_KYBER */
15441
        }
15442
    }
15443
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
15444
15445
0
#ifdef HAVE_FFDHE
15446
0
    if (ssl->namedGroup != 0) {
15447
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
15448
0
    }
15449
0
#endif
15450
15451
0
#ifdef HAVE_CURVE25519
15452
0
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
15453
0
        cName = "X25519";
15454
0
    }
15455
0
#endif
15456
15457
0
#ifdef HAVE_CURVE448
15458
0
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
15459
0
        cName = "X448";
15460
0
    }
15461
0
#endif
15462
15463
0
#ifdef HAVE_ECC
15464
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
15465
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
15466
0
                                NULL));
15467
0
    }
15468
0
#endif
15469
15470
0
    return cName;
15471
0
}
15472
#endif
15473
15474
#ifdef OPENSSL_EXTRA
15475
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
15476
/* return authentication NID corresponding to cipher suite
15477
 * @param cipher a pointer to WOLFSSL_CIPHER
15478
 * return NID if found, WC_NID_undef if not found
15479
 */
15480
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
15481
{
15482
    static const struct authnid {
15483
        const char* alg_name;
15484
        const int  nid;
15485
    } authnid_tbl[] = {
15486
        {"RSA",     WC_NID_auth_rsa},
15487
        {"PSK",     WC_NID_auth_psk},
15488
        {"SRP",     WC_NID_auth_srp},
15489
        {"ECDSA",   WC_NID_auth_ecdsa},
15490
        {"None",    WC_NID_auth_null},
15491
        {NULL,      WC_NID_undef}
15492
    };
15493
15494
    const char* authStr;
15495
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15496
15497
    if (GetCipherSegment(cipher, n) == NULL) {
15498
        WOLFSSL_MSG("no suitable cipher name found");
15499
        return WC_NID_undef;
15500
    }
15501
15502
    authStr = GetCipherAuthStr(n);
15503
15504
    if (authStr != NULL) {
15505
        const struct authnid* sa;
15506
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
15507
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
15508
                return sa->nid;
15509
            }
15510
        }
15511
    }
15512
15513
    return WC_NID_undef;
15514
}
15515
/* return cipher NID corresponding to cipher suite
15516
 * @param cipher a pointer to WOLFSSL_CIPHER
15517
 * return NID if found, WC_NID_undef if not found
15518
 */
15519
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
15520
{
15521
    static const struct ciphernid {
15522
        const char* alg_name;
15523
        const int  nid;
15524
    } ciphernid_tbl[] = {
15525
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
15526
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
15527
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
15528
        {"AES(128)",                WC_NID_aes_128_cbc},
15529
        {"AES(256)",                WC_NID_aes_256_cbc},
15530
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
15531
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
15532
        {"RC4",                     WC_NID_rc4},
15533
        {"3DES",                    WC_NID_des_ede3_cbc},
15534
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
15535
        {"None",                    WC_NID_undef},
15536
        {NULL,                      WC_NID_undef}
15537
    };
15538
15539
    const char* encStr;
15540
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15541
15542
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
15543
15544
    if (GetCipherSegment(cipher, n) == NULL) {
15545
        WOLFSSL_MSG("no suitable cipher name found");
15546
        return WC_NID_undef;
15547
    }
15548
15549
    encStr = GetCipherEncStr(n);
15550
15551
    if (encStr != NULL) {
15552
        const struct ciphernid* c;
15553
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
15554
            if (XSTRCMP(c->alg_name, encStr) == 0) {
15555
                return c->nid;
15556
            }
15557
        }
15558
    }
15559
15560
    return WC_NID_undef;
15561
}
15562
/* return digest NID corresponding to cipher suite
15563
 * @param cipher a pointer to WOLFSSL_CIPHER
15564
 * return NID if found, WC_NID_undef if not found
15565
 */
15566
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
15567
{
15568
    static const struct macnid {
15569
        const char* alg_name;
15570
        const int  nid;
15571
    } macnid_tbl[] = {
15572
        {"SHA1",    WC_NID_sha1},
15573
        {"SHA256",  WC_NID_sha256},
15574
        {"SHA384",  WC_NID_sha384},
15575
        {NULL,      WC_NID_undef}
15576
    };
15577
15578
    const char* name;
15579
    const char* macStr;
15580
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15581
    (void)name;
15582
15583
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
15584
15585
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
15586
        WOLFSSL_MSG("no suitable cipher name found");
15587
        return WC_NID_undef;
15588
    }
15589
15590
    /* in MD5 case, NID will be WC_NID_md5 */
15591
    if (XSTRSTR(name, "MD5") != NULL) {
15592
        return WC_NID_md5;
15593
    }
15594
15595
    macStr = GetCipherMacStr(n);
15596
15597
    if (macStr != NULL) {
15598
        const struct macnid* mc;
15599
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
15600
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
15601
                return mc->nid;
15602
            }
15603
        }
15604
    }
15605
15606
    return WC_NID_undef;
15607
}
15608
/* return key exchange NID corresponding to cipher suite
15609
 * @param cipher a pointer to WOLFSSL_CIPHER
15610
 * return NID if found, WC_NID_undef if not found
15611
 */
15612
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
15613
{
15614
    static const struct kxnid {
15615
        const char* name;
15616
        const int  nid;
15617
    } kxnid_table[] = {
15618
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
15619
        {"ECDH",      WC_NID_kx_ecdhe},
15620
        {"DHEPSK",    WC_NID_kx_dhe_psk},
15621
        {"DH",        WC_NID_kx_dhe},
15622
        {"RSAPSK",    WC_NID_kx_rsa_psk},
15623
        {"SRP",       WC_NID_kx_srp},
15624
        {"EDH",       WC_NID_kx_dhe},
15625
        {"RSA",       WC_NID_kx_rsa},
15626
        {NULL,        WC_NID_undef}
15627
    };
15628
15629
    const char* keaStr;
15630
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15631
15632
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
15633
15634
    if (GetCipherSegment(cipher, n) == NULL) {
15635
        WOLFSSL_MSG("no suitable cipher name found");
15636
        return WC_NID_undef;
15637
    }
15638
15639
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
15640
    if (XSTRCMP(n[0], "TLS13") == 0) {
15641
        return WC_NID_kx_any;
15642
    }
15643
15644
    keaStr = GetCipherKeaStr(n);
15645
15646
    if (keaStr != NULL) {
15647
        const struct kxnid* k;
15648
        for(k = kxnid_table; k->name != NULL; k++) {
15649
            if (XSTRCMP(k->name, keaStr) == 0) {
15650
                return k->nid;
15651
            }
15652
        }
15653
    }
15654
15655
    return WC_NID_undef;
15656
}
15657
/* check if cipher suite is AEAD
15658
 * @param cipher a pointer to WOLFSSL_CIPHER
15659
 * return 1 if cipher is AEAD, 0 otherwise
15660
 */
15661
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
15662
{
15663
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15664
15665
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
15666
15667
    if (GetCipherSegment(cipher, n) == NULL) {
15668
        WOLFSSL_MSG("no suitable cipher name found");
15669
        return WC_NID_undef;
15670
    }
15671
15672
    return IsCipherAEAD(n);
15673
}
15674
/* Creates cipher->description based on cipher->offset
15675
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
15676
 * to a stack of ciphers.
15677
 * @param [in] cipher: A cipher from a stack of ciphers.
15678
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
15679
 */
15680
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
15681
{
15682
    int strLen;
15683
    unsigned long offset;
15684
    char* dp;
15685
    const char* name;
15686
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
15687
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
15688
    int len = MAX_DESCRIPTION_SZ-1;
15689
    const CipherSuiteInfo* cipher_names;
15690
    ProtocolVersion pv;
15691
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
15692
15693
    if (cipher == NULL)
15694
        return WOLFSSL_FAILURE;
15695
15696
    dp = cipher->description;
15697
    if (dp == NULL)
15698
        return WOLFSSL_FAILURE;
15699
15700
    cipher_names = GetCipherNames();
15701
15702
    offset = cipher->offset;
15703
    if (offset >= (unsigned long)GetCipherNamesSize())
15704
        return WOLFSSL_FAILURE;
15705
    pv.major = cipher_names[offset].major;
15706
    pv.minor = cipher_names[offset].minor;
15707
    protocol = wolfSSL_internal_get_version(&pv);
15708
15709
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
15710
        WOLFSSL_MSG("no suitable cipher name found");
15711
        return WOLFSSL_FAILURE;
15712
    }
15713
15714
    /* keaStr */
15715
    keaStr = GetCipherKeaStr(n);
15716
    /* authStr */
15717
    authStr = GetCipherAuthStr(n);
15718
    /* encStr */
15719
    encStr = GetCipherEncStr(n);
15720
    if ((cipher->bits = SetCipherBits(encStr)) ==
15721
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
15722
    {
15723
       WOLFSSL_MSG("Cipher Bits Not Set.");
15724
    }
15725
    /* macStr */
15726
    macStr = GetCipherMacStr(n);
15727
15728
15729
    /* Build up the string by copying onto the end. */
15730
    XSTRNCPY(dp, name, (size_t)len);
15731
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15732
    len -= strLen; dp += strLen;
15733
15734
    XSTRNCPY(dp, " ", (size_t)len);
15735
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15736
    len -= strLen; dp += strLen;
15737
    XSTRNCPY(dp, protocol, (size_t)len);
15738
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15739
    len -= strLen; dp += strLen;
15740
15741
    XSTRNCPY(dp, " Kx=", (size_t)len);
15742
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15743
    len -= strLen; dp += strLen;
15744
    XSTRNCPY(dp, keaStr, (size_t)len);
15745
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15746
    len -= strLen; dp += strLen;
15747
15748
    XSTRNCPY(dp, " Au=", (size_t)len);
15749
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15750
    len -= strLen; dp += strLen;
15751
    XSTRNCPY(dp, authStr, (size_t)len);
15752
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15753
    len -= strLen; dp += strLen;
15754
15755
    XSTRNCPY(dp, " Enc=", (size_t)len);
15756
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15757
    len -= strLen; dp += strLen;
15758
    XSTRNCPY(dp, encStr, (size_t)len);
15759
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15760
    len -= strLen; dp += strLen;
15761
15762
    XSTRNCPY(dp, " Mac=", (size_t)len);
15763
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
15764
    len -= strLen; dp += (size_t)strLen;
15765
    XSTRNCPY(dp, macStr, (size_t)len);
15766
    dp[len-1] = '\0';
15767
15768
    return WOLFSSL_SUCCESS;
15769
}
15770
#endif /* OPENSSL_ALL || WOLFSSL_QT */
15771
15772
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
15773
{
15774
    const char* keaStr;
15775
15776
    switch (kea) {
15777
        case no_kea:
15778
            keaStr = "None";
15779
            break;
15780
#ifndef NO_RSA
15781
        case rsa_kea:
15782
            keaStr = "RSA";
15783
            break;
15784
#endif
15785
#ifndef NO_DH
15786
        case diffie_hellman_kea:
15787
            keaStr = "DHE";
15788
            break;
15789
#endif
15790
        case fortezza_kea:
15791
            keaStr = "FZ";
15792
            break;
15793
#ifndef NO_PSK
15794
        case psk_kea:
15795
            keaStr = "PSK";
15796
            break;
15797
    #ifndef NO_DH
15798
        case dhe_psk_kea:
15799
            keaStr = "DHEPSK";
15800
            break;
15801
    #endif
15802
    #ifdef HAVE_ECC
15803
        case ecdhe_psk_kea:
15804
            keaStr = "ECDHEPSK";
15805
            break;
15806
    #endif
15807
#endif
15808
#ifdef HAVE_ECC
15809
        case ecc_diffie_hellman_kea:
15810
            keaStr = "ECDHE";
15811
            break;
15812
        case ecc_static_diffie_hellman_kea:
15813
            keaStr = "ECDH";
15814
            break;
15815
#endif
15816
        case any_kea:
15817
            keaStr = "any";
15818
            break;
15819
        default:
15820
            keaStr = "unknown";
15821
            break;
15822
    }
15823
15824
    return keaStr;
15825
}
15826
15827
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
15828
{
15829
    const char* authStr;
15830
15831
    switch (sig_algo) {
15832
        case anonymous_sa_algo:
15833
            authStr = "None";
15834
            break;
15835
#ifndef NO_RSA
15836
        case rsa_sa_algo:
15837
            authStr = "RSA";
15838
            break;
15839
    #ifdef WC_RSA_PSS
15840
        case rsa_pss_sa_algo:
15841
            authStr = "RSA-PSS";
15842
            break;
15843
    #endif
15844
#endif
15845
#ifndef NO_DSA
15846
        case dsa_sa_algo:
15847
            authStr = "DSA";
15848
            break;
15849
#endif
15850
#ifdef HAVE_ECC
15851
        case ecc_dsa_sa_algo:
15852
            authStr = "ECDSA";
15853
            break;
15854
#endif
15855
#ifdef WOLFSSL_SM2
15856
        case sm2_sa_algo:
15857
            authStr = "SM2";
15858
            break;
15859
#endif
15860
#ifdef HAVE_ED25519
15861
        case ed25519_sa_algo:
15862
            authStr = "Ed25519";
15863
            break;
15864
#endif
15865
#ifdef HAVE_ED448
15866
        case ed448_sa_algo:
15867
            authStr = "Ed448";
15868
            break;
15869
#endif
15870
        case any_sa_algo:
15871
            authStr = "any";
15872
            break;
15873
        default:
15874
            authStr = "unknown";
15875
            break;
15876
    }
15877
15878
    return authStr;
15879
}
15880
15881
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
15882
{
15883
    const char* encStr;
15884
15885
    (void)key_size;
15886
15887
    switch (cipher) {
15888
        case wolfssl_cipher_null:
15889
            encStr = "None";
15890
            break;
15891
#ifndef NO_RC4
15892
        case wolfssl_rc4:
15893
            encStr = "RC4(128)";
15894
            break;
15895
#endif
15896
#ifndef NO_DES3
15897
        case wolfssl_triple_des:
15898
            encStr = "3DES(168)";
15899
            break;
15900
#endif
15901
#ifndef NO_AES
15902
        case wolfssl_aes:
15903
            if (key_size == AES_128_KEY_SIZE)
15904
                encStr = "AES(128)";
15905
            else if (key_size == AES_256_KEY_SIZE)
15906
                encStr = "AES(256)";
15907
            else
15908
                encStr = "AES(?)";
15909
            break;
15910
    #ifdef HAVE_AESGCM
15911
        case wolfssl_aes_gcm:
15912
            if (key_size == AES_128_KEY_SIZE)
15913
                encStr = "AESGCM(128)";
15914
            else if (key_size == AES_256_KEY_SIZE)
15915
                encStr = "AESGCM(256)";
15916
            else
15917
                encStr = "AESGCM(?)";
15918
            break;
15919
    #endif
15920
    #ifdef HAVE_AESCCM
15921
        case wolfssl_aes_ccm:
15922
            if (key_size == AES_128_KEY_SIZE)
15923
                encStr = "AESCCM(128)";
15924
            else if (key_size == AES_256_KEY_SIZE)
15925
                encStr = "AESCCM(256)";
15926
            else
15927
                encStr = "AESCCM(?)";
15928
            break;
15929
    #endif
15930
#endif
15931
#ifdef HAVE_CHACHA
15932
        case wolfssl_chacha:
15933
            encStr = "CHACHA20/POLY1305(256)";
15934
            break;
15935
#endif
15936
#ifdef HAVE_ARIA
15937
        case wolfssl_aria_gcm:
15938
            if (key_size == ARIA_128_KEY_SIZE)
15939
                encStr = "Aria(128)";
15940
            else if (key_size == ARIA_192_KEY_SIZE)
15941
                encStr = "Aria(192)";
15942
            else if (key_size == ARIA_256_KEY_SIZE)
15943
                encStr = "Aria(256)";
15944
            else
15945
                encStr = "Aria(?)";
15946
            break;
15947
#endif
15948
#ifdef HAVE_CAMELLIA
15949
        case wolfssl_camellia:
15950
            if (key_size == CAMELLIA_128_KEY_SIZE)
15951
                encStr = "Camellia(128)";
15952
            else if (key_size == CAMELLIA_256_KEY_SIZE)
15953
                encStr = "Camellia(256)";
15954
            else
15955
                encStr = "Camellia(?)";
15956
            break;
15957
#endif
15958
        default:
15959
            encStr = "unknown";
15960
            break;
15961
    }
15962
15963
    return encStr;
15964
}
15965
15966
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
15967
{
15968
    const char* macStr;
15969
15970
    switch (mac) {
15971
        case no_mac:
15972
            macStr = "None";
15973
            break;
15974
#ifndef NO_MD5
15975
        case md5_mac:
15976
            macStr = "MD5";
15977
            break;
15978
#endif
15979
#ifndef NO_SHA
15980
        case sha_mac:
15981
            macStr = "SHA1";
15982
            break;
15983
#endif
15984
#ifdef WOLFSSL_SHA224
15985
        case sha224_mac:
15986
            macStr = "SHA224";
15987
            break;
15988
#endif
15989
#ifndef NO_SHA256
15990
        case sha256_mac:
15991
            macStr = "SHA256";
15992
            break;
15993
#endif
15994
#ifdef WOLFSSL_SHA384
15995
        case sha384_mac:
15996
            macStr = "SHA384";
15997
            break;
15998
#endif
15999
#ifdef WOLFSSL_SHA512
16000
        case sha512_mac:
16001
            macStr = "SHA512";
16002
            break;
16003
#endif
16004
        default:
16005
            macStr = "unknown";
16006
            break;
16007
    }
16008
16009
    return macStr;
16010
}
16011
16012
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
16013
                                 int len)
16014
{
16015
    char *ret = in;
16016
    const char *keaStr, *authStr, *encStr, *macStr;
16017
    size_t strLen;
16018
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
16019
16020
    if (cipher == NULL || in == NULL)
16021
        return NULL;
16022
16023
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
16024
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
16025
     * Return the description based on cipher_names[cipher->offset]
16026
     */
16027
    if (cipher->in_stack == TRUE) {
16028
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
16029
        XSTRNCPY(in,cipher->description,(size_t)len);
16030
        return ret;
16031
    }
16032
#endif
16033
16034
    /* Get the cipher description based on the SSL session cipher */
16035
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
16036
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
16037
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
16038
                                      cipher->ssl->specs.key_size);
16039
    if (cipher->ssl->specs.cipher_type == aead)
16040
        macStr = "AEAD";
16041
    else
16042
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
16043
16044
    /* Build up the string by copying onto the end. */
16045
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
16046
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16047
16048
    XSTRNCPY(in, " ", (size_t)len);
16049
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16050
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
16051
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16052
16053
    XSTRNCPY(in, " Kx=", (size_t)len);
16054
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16055
    XSTRNCPY(in, keaStr, (size_t)len);
16056
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16057
16058
    XSTRNCPY(in, " Au=", (size_t)len);
16059
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16060
    XSTRNCPY(in, authStr, (size_t)len);
16061
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16062
16063
    XSTRNCPY(in, " Enc=", (size_t)len);
16064
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16065
    XSTRNCPY(in, encStr, (size_t)len);
16066
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16067
16068
    XSTRNCPY(in, " Mac=", (size_t)len);
16069
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
16070
    XSTRNCPY(in, macStr, (size_t)len);
16071
    in[len-1] = '\0';
16072
16073
    return ret;
16074
}
16075
16076
int wolfSSL_OCSP_parse_url(const char* url, char** host, char** port,
16077
        char** path, int* ssl)
16078
{
16079
    const char* u = url;
16080
    const char* upath; /* path in u */
16081
    const char* uport; /* port in u */
16082
    const char* hostEnd;
16083
16084
    WOLFSSL_ENTER("OCSP_parse_url");
16085
16086
    *host = NULL;
16087
    *port = NULL;
16088
    *path = NULL;
16089
    *ssl = 0;
16090
16091
    if (*(u++) != 'h') goto err;
16092
    if (*(u++) != 't') goto err;
16093
    if (*(u++) != 't') goto err;
16094
    if (*(u++) != 'p') goto err;
16095
    if (*u == 's') {
16096
        *ssl = 1;
16097
        u++;
16098
        *port = CopyString("443", -1, NULL, DYNAMIC_TYPE_OPENSSL);
16099
    }
16100
    else if (*u == ':') {
16101
        *ssl = 0;
16102
        *port = CopyString("80", -1, NULL, DYNAMIC_TYPE_OPENSSL);
16103
    }
16104
    else
16105
        goto err;
16106
    if (*port == NULL)
16107
        goto err;
16108
    if (*(u++) != ':') goto err;
16109
    if (*(u++) != '/') goto err;
16110
    if (*(u++) != '/') goto err;
16111
16112
    /* Look for path */
16113
    upath = XSTRSTR(u, "/");
16114
    *path = CopyString(upath == NULL ? "/" : upath, -1, NULL,
16115
                       DYNAMIC_TYPE_OPENSSL);
16116
16117
    /* Look for port */
16118
    uport = XSTRSTR(u, ":");
16119
    if (uport != NULL) {
16120
        if (*(++uport) == '\0')
16121
            goto err;
16122
        /* port must be before path */
16123
        if (upath != NULL && uport >= upath)
16124
            goto err;
16125
        XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
16126
        *port = CopyString(uport, upath != NULL ? (int)(upath - uport) : -1,
16127
                           NULL, DYNAMIC_TYPE_OPENSSL);
16128
        if (*port == NULL)
16129
            goto err;
16130
        hostEnd = uport - 1;
16131
    }
16132
    else
16133
        hostEnd = upath;
16134
16135
    *host = CopyString(u, hostEnd != NULL ? (int)(hostEnd - u) : -1, NULL,
16136
                       DYNAMIC_TYPE_OPENSSL);
16137
    if (*host == NULL)
16138
        goto err;
16139
16140
    return WOLFSSL_SUCCESS;
16141
err:
16142
    XFREE(*host, NULL, DYNAMIC_TYPE_OPENSSL);
16143
    *host = NULL;
16144
    XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL);
16145
    *port = NULL;
16146
    XFREE(*path, NULL, DYNAMIC_TYPE_OPENSSL);
16147
    *path = NULL;
16148
    return WOLFSSL_FAILURE;
16149
}
16150
16151
#ifndef NO_WOLFSSL_STUB
16152
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
16153
{
16154
    WOLFSSL_STUB("COMP_zlib");
16155
    return 0;
16156
}
16157
16158
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
16159
{
16160
    WOLFSSL_STUB("COMP_rle");
16161
    return 0;
16162
}
16163
16164
int wolfSSL_COMP_add_compression_method(int method, void* data)
16165
{
16166
    (void)method;
16167
    (void)data;
16168
    WOLFSSL_STUB("COMP_add_compression_method");
16169
    return 0;
16170
}
16171
16172
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
16173
    (void)ssl;
16174
    return NULL;
16175
}
16176
16177
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
16178
    (void)ssl;
16179
    return NULL;
16180
}
16181
16182
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
16183
{
16184
    static const char ret[] = "not supported";
16185
16186
    (void)comp;
16187
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
16188
    return ret;
16189
}
16190
#endif
16191
16192
/*  wolfSSL_set_dynlock_create_callback
16193
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
16194
 *  This function exists for compatibility purposes because wolfSSL satisfies
16195
 *  thread safety without relying on the callback.
16196
 */
16197
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
16198
                                                          const char*, int))
16199
{
16200
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
16201
    (void)f;
16202
}
16203
/*  wolfSSL_set_dynlock_lock_callback
16204
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
16205
 *  This function exists for compatibility purposes because wolfSSL satisfies
16206
 *  thread safety without relying on the callback.
16207
 */
16208
void wolfSSL_set_dynlock_lock_callback(
16209
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
16210
{
16211
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
16212
    (void)f;
16213
}
16214
/*  wolfSSL_set_dynlock_destroy_callback
16215
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
16216
 *  This function exists for compatibility purposes because wolfSSL satisfies
16217
 *  thread safety without relying on the callback.
16218
 */
16219
void wolfSSL_set_dynlock_destroy_callback(
16220
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
16221
{
16222
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
16223
    (void)f;
16224
}
16225
16226
16227
#endif /* OPENSSL_EXTRA */
16228
16229
#ifdef OPENSSL_EXTRA
16230
#ifndef NO_CERTS
16231
16232
#if !defined(NO_ASN) && !defined(NO_PWDBASED)
16233
/* Copies unencrypted DER key buffer into "der". If "der" is null then the size
16234
 * of buffer needed is returned. If *der == NULL then it allocates a buffer.
16235
 * NOTE: This also advances the "der" pointer to be at the end of buffer.
16236
 *
16237
 * Returns size of key buffer on success
16238
 */
16239
int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der)
16240
{
16241
    return wolfSSL_EVP_PKEY_get_der(key, der);
16242
}
16243
16244
int wolfSSL_i2d_PrivateKey_bio(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
16245
{
16246
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
16247
    int derSz = 0;
16248
    byte* der = NULL;
16249
16250
    if (bio == NULL || key == NULL) {
16251
        return WOLFSSL_FAILURE;
16252
    }
16253
16254
    derSz = wolfSSL_i2d_PrivateKey(key, NULL);
16255
    if (derSz <= 0) {
16256
        WOLFSSL_MSG("wolfSSL_i2d_PrivateKey (for getting size) failed");
16257
        return WOLFSSL_FAILURE;
16258
    }
16259
16260
    der = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
16261
    if (!der) {
16262
        WOLFSSL_MSG("malloc failed");
16263
        return WOLFSSL_FAILURE;
16264
    }
16265
16266
    derSz = wolfSSL_i2d_PrivateKey(key, &der);
16267
    if (derSz <= 0) {
16268
        WOLFSSL_MSG("wolfSSL_i2d_PrivateKey failed");
16269
        goto cleanup;
16270
    }
16271
16272
    if (wolfSSL_BIO_write(bio, der, derSz) != derSz) {
16273
        goto cleanup;
16274
    }
16275
16276
    ret = WOLFSSL_SUCCESS;
16277
16278
cleanup:
16279
    XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
16280
    return ret;
16281
}
16282
16283
int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der)
16284
{
16285
#if !defined(NO_RSA) || defined(HAVE_ECC)
16286
#ifdef HAVE_ECC
16287
    unsigned char *local_der = NULL;
16288
    word32 local_derSz = 0;
16289
    unsigned char *pub_der = NULL;
16290
    ecc_key *eccKey = NULL;
16291
    word32 inOutIdx = 0;
16292
#endif
16293
    word32 pub_derSz = 0;
16294
    int ret;
16295
    int key_type = 0;
16296
16297
    if (key == NULL) {
16298
        return WOLFSSL_FATAL_ERROR;
16299
    }
16300
16301
    key_type = key->type;
16302
    if ((key_type != WC_EVP_PKEY_EC) && (key_type != WC_EVP_PKEY_RSA)) {
16303
        return WOLFSSL_FATAL_ERROR;
16304
    }
16305
16306
#ifndef NO_RSA
16307
    if (key_type == WC_EVP_PKEY_RSA) {
16308
        return wolfSSL_i2d_RSAPublicKey(key->rsa, der);
16309
    }
16310
#endif
16311
16312
    /* Now that RSA is taken care of, we only need to consider the ECC case. */
16313
16314
#ifdef HAVE_ECC
16315
16316
    /* We need to get the DER, then convert it to a public key. But what we get
16317
     * might be a buffered private key so we need to decode it and then encode
16318
     * the public part. */
16319
    ret = wolfSSL_EVP_PKEY_get_der(key, &local_der);
16320
    if (ret <= 0) {
16321
        /* In this case, there was no buffered DER at all. This could be the
16322
         * case where the key that was passed in was generated. So now we
16323
         * have to create the local DER. */
16324
        local_derSz = (word32)wolfSSL_i2d_ECPrivateKey(key->ecc, &local_der);
16325
        if (local_derSz == 0) {
16326
            ret = WOLFSSL_FATAL_ERROR;
16327
        }
16328
    } else {
16329
        local_derSz = (word32)ret;
16330
        ret = 0;
16331
    }
16332
16333
    if (ret == 0) {
16334
        eccKey = (ecc_key *)XMALLOC(sizeof(*eccKey), NULL, DYNAMIC_TYPE_ECC);
16335
        if (eccKey == NULL) {
16336
            WOLFSSL_MSG("Failed to allocate key buffer.");
16337
            ret = WOLFSSL_FATAL_ERROR;
16338
        }
16339
    }
16340
16341
    if (ret == 0) {
16342
        ret = wc_ecc_init(eccKey);
16343
    }
16344
16345
    if (ret == 0) {
16346
        ret = wc_EccPublicKeyDecode(local_der, &inOutIdx, eccKey, local_derSz);
16347
        if (ret < 0) {
16348
            /* We now try again as x.963 [point type][x][opt y]. */
16349
            ret = wc_ecc_import_x963(local_der, local_derSz, eccKey);
16350
        }
16351
    }
16352
16353
    if (ret == 0) {
16354
        pub_derSz = (word32)wc_EccPublicKeyDerSize(eccKey, 1);
16355
        if ((int)pub_derSz <= 0) {
16356
            ret = WOLFSSL_FAILURE;
16357
        }
16358
    }
16359
16360
    if (ret == 0) {
16361
        pub_der = (unsigned char*)XMALLOC(pub_derSz, NULL,
16362
                                          DYNAMIC_TYPE_PUBLIC_KEY);
16363
        if (pub_der == NULL) {
16364
            WOLFSSL_MSG("Failed to allocate output buffer.");
16365
            ret = WOLFSSL_FATAL_ERROR;
16366
        }
16367
    }
16368
16369
    if (ret == 0) {
16370
        pub_derSz = (word32)wc_EccPublicKeyToDer(eccKey, pub_der, pub_derSz, 1);
16371
        if ((int)pub_derSz <= 0) {
16372
            ret = WOLFSSL_FATAL_ERROR;
16373
        }
16374
    }
16375
16376
    /* This block is for actually returning the DER of the public key */
16377
    if ((ret == 0) && (der != NULL)) {
16378
        if (*der == NULL) {
16379
            *der = (unsigned char*)XMALLOC(pub_derSz, NULL,
16380
                                           DYNAMIC_TYPE_PUBLIC_KEY);
16381
            if (*der == NULL) {
16382
                WOLFSSL_MSG("Failed to allocate output buffer.");
16383
                ret = WOLFSSL_FATAL_ERROR;
16384
            }
16385
16386
            if (ret == 0) {
16387
                XMEMCPY(*der, pub_der, pub_derSz);
16388
            }
16389
        }
16390
        else {
16391
            XMEMCPY(*der, pub_der, pub_derSz);
16392
            *der += pub_derSz;
16393
        }
16394
    }
16395
16396
    XFREE(pub_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
16397
    XFREE(local_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
16398
16399
    wc_ecc_free(eccKey);
16400
    XFREE(eccKey, NULL, DYNAMIC_TYPE_ECC);
16401
16402
#else
16403
    ret = WOLFSSL_FATAL_ERROR;
16404
#endif /* HAVE_ECC */
16405
16406
    if (ret == 0) {
16407
        return (int)pub_derSz;
16408
    }
16409
16410
    return ret;
16411
#else
16412
    return WOLFSSL_FATAL_ERROR;
16413
#endif /* !NO_RSA || HAVE_ECC */
16414
}
16415
#endif /* !NO_ASN && !NO_PWDBASED */
16416
16417
#endif /* !NO_CERTS */
16418
#endif /* OPENSSL_EXTRA */
16419
16420
#ifdef OPENSSL_EXTRA
16421
16422
/* Sets the DNS hostname to name.
16423
 * Hostname is cleared if name is NULL or empty. */
16424
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
16425
{
16426
    if (ssl == NULL) {
16427
        return WOLFSSL_FAILURE;
16428
    }
16429
16430
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
16431
}
16432
16433
/******************************************************************************
16434
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
16435
*
16436
* RETURNS:
16437
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
16438
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
16439
*   same as openssl.
16440
*/
16441
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
16442
{
16443
    if (ctx == NULL || vpm == NULL)
16444
        return WOLFSSL_SUCCESS;
16445
16446
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
16447
}
16448
16449
/******************************************************************************
16450
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
16451
*
16452
* RETURNS:
16453
* returns pointer to the SSL verification parameters on success,
16454
* otherwise returns NULL
16455
*/
16456
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
16457
{
16458
    if (ctx == NULL) {
16459
        return NULL;
16460
    }
16461
16462
    return ctx->param;
16463
}
16464
16465
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
16466
{
16467
    if (ssl == NULL) {
16468
        return NULL;
16469
    }
16470
    return ssl->param;
16471
}
16472
16473
#endif /* OPENSSL_EXTRA */
16474
16475
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
16476
/* Gets an index to store SSL structure at.
16477
 *
16478
 * Returns positive index on success and negative values on failure
16479
 */
16480
int wolfSSL_get_ex_data_X509_STORE_CTX_idx(void)
16481
{
16482
    WOLFSSL_ENTER("wolfSSL_get_ex_data_X509_STORE_CTX_idx");
16483
16484
    /* store SSL at index 0 */
16485
    return 0;
16486
}
16487
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
16488
16489
#ifdef OPENSSL_EXTRA
16490
/* Sets a function callback that will send information about the state of all
16491
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
16492
 * in.
16493
 *
16494
 * ctx WOLFSSL_CTX structure to set callback function in
16495
 * f   callback function to use
16496
 */
16497
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
16498
       void (*f)(const WOLFSSL* ssl, int type, int val))
16499
{
16500
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
16501
    if (ctx == NULL) {
16502
        WOLFSSL_MSG("Bad function argument");
16503
    }
16504
    else {
16505
        ctx->CBIS = f;
16506
    }
16507
}
16508
16509
void wolfSSL_set_info_callback(WOLFSSL* ssl,
16510
       void (*f)(const WOLFSSL* ssl, int type, int val))
16511
{
16512
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
16513
    if (ssl == NULL) {
16514
        WOLFSSL_MSG("Bad function argument");
16515
    }
16516
    else {
16517
        ssl->CBIS = f;
16518
    }
16519
}
16520
16521
16522
unsigned long wolfSSL_ERR_peek_error(void)
16523
{
16524
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error");
16525
16526
    return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL);
16527
}
16528
16529
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H
16530
#include <wolfssl/debug-untrace-error-codes.h>
16531
#endif
16532
16533
int wolfSSL_ERR_GET_LIB(unsigned long err)
16534
{
16535
    unsigned long value;
16536
16537
    value = (err & 0xFFFFFFL);
16538
    switch (value) {
16539
    case -PARSE_ERROR:
16540
        return WOLFSSL_ERR_LIB_SSL;
16541
    case -ASN_NO_PEM_HEADER:
16542
    case -WOLFSSL_PEM_R_NO_START_LINE_E:
16543
    case -WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E:
16544
    case -WOLFSSL_PEM_R_BAD_PASSWORD_READ_E:
16545
    case -WOLFSSL_PEM_R_BAD_DECRYPT_E:
16546
        return WOLFSSL_ERR_LIB_PEM;
16547
    case -WOLFSSL_EVP_R_BAD_DECRYPT_E:
16548
    case -WOLFSSL_EVP_R_BN_DECODE_ERROR:
16549
    case -WOLFSSL_EVP_R_DECODE_ERROR:
16550
    case -WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR:
16551
        return WOLFSSL_ERR_LIB_EVP;
16552
    case -WOLFSSL_ASN1_R_HEADER_TOO_LONG_E:
16553
        return WOLFSSL_ERR_LIB_ASN1;
16554
    default:
16555
        return 0;
16556
    }
16557
}
16558
16559
#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES
16560
#include <wolfssl/debug-trace-error-codes.h>
16561
#endif
16562
16563
/* This function is to find global error values that are the same through out
16564
 * all library version. With wolfSSL having only one set of error codes the
16565
 * return value is pretty straight forward. The only thing needed is all wolfSSL
16566
 * error values are typically negative.
16567
 *
16568
 * Returns the error reason
16569
 */
16570
int wolfSSL_ERR_GET_REASON(unsigned long err)
16571
{
16572
    int ret = (int)err;
16573
16574
    WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON");
16575
16576
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
16577
    /* Nginx looks for this error to know to stop parsing certificates.
16578
     * Same for HAProxy. */
16579
    if (err == ((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE) ||
16580
       ((err & 0xFFFFFFL) == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) ||
16581
       ((err & 0xFFFL) == PEM_R_NO_START_LINE ))
16582
        return PEM_R_NO_START_LINE;
16583
    if (err == ((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST))
16584
        return SSL_R_HTTP_REQUEST;
16585
#endif
16586
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
16587
    if (err == ((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG))
16588
        return ASN1_R_HEADER_TOO_LONG;
16589
#endif
16590
16591
    /* check if error value is in range of wolfCrypt or wolfSSL errors */
16592
    ret = 0 - ret; /* setting as negative value */
16593
16594
    if ((ret <= WC_SPAN1_FIRST_E && ret >= WC_SPAN1_LAST_E) ||
16595
        (ret <= WC_SPAN2_FIRST_E && ret >= WC_SPAN2_LAST_E) ||
16596
        (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E))
16597
    {
16598
        return ret;
16599
    }
16600
    else {
16601
        WOLFSSL_MSG("Not in range of typical error values");
16602
        ret = (int)err;
16603
    }
16604
16605
    return ret;
16606
}
16607
16608
#ifndef NO_TLS
16609
/* returns a string that describes the alert
16610
 *
16611
 * alertID the alert value to look up
16612
 */
16613
const char* wolfSSL_alert_type_string_long(int alertID)
16614
{
16615
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
16616
16617
    return AlertTypeToString(alertID);
16618
}
16619
16620
const char* wolfSSL_alert_desc_string_long(int alertID)
16621
{
16622
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
16623
16624
    return AlertTypeToString(alertID);
16625
}
16626
#endif /* !NO_TLS */
16627
16628
#define STATE_STRINGS_PROTO(s) \
16629
    {                          \
16630
        {"SSLv3 " s,           \
16631
         "SSLv3 " s,           \
16632
         "SSLv3 " s},          \
16633
        {"TLSv1 " s,           \
16634
         "TLSv1 " s,           \
16635
         "TLSv1 " s},          \
16636
        {"TLSv1_1 " s,         \
16637
         "TLSv1_1 " s,         \
16638
         "TLSv1_1 " s},        \
16639
        {"TLSv1_2 " s,         \
16640
         "TLSv1_2 " s,         \
16641
         "TLSv1_2 " s},        \
16642
        {"TLSv1_3 " s,         \
16643
         "TLSv1_3 " s,         \
16644
         "TLSv1_3 " s},        \
16645
        {"DTLSv1 " s,          \
16646
         "DTLSv1 " s,          \
16647
         "DTLSv1 " s},         \
16648
        {"DTLSv1_2 " s,        \
16649
         "DTLSv1_2 " s,        \
16650
         "DTLSv1_2 " s},       \
16651
        {"DTLSv1_3 " s,        \
16652
         "DTLSv1_3 " s,        \
16653
         "DTLSv1_3 " s},       \
16654
    }
16655
16656
#define STATE_STRINGS_PROTO_RW(s) \
16657
    {                             \
16658
        {"SSLv3 read " s,         \
16659
         "SSLv3 write " s,        \
16660
         "SSLv3 " s},             \
16661
        {"TLSv1 read " s,         \
16662
         "TLSv1 write " s,        \
16663
         "TLSv1 " s},             \
16664
        {"TLSv1_1 read " s,       \
16665
         "TLSv1_1 write " s,      \
16666
         "TLSv1_1 " s},           \
16667
        {"TLSv1_2 read " s,       \
16668
         "TLSv1_2 write " s,      \
16669
         "TLSv1_2 " s},           \
16670
        {"TLSv1_3 read " s,       \
16671
         "TLSv1_3 write " s,      \
16672
         "TLSv1_3 " s},           \
16673
        {"DTLSv1 read " s,        \
16674
         "DTLSv1 write " s,       \
16675
         "DTLSv1 " s},            \
16676
        {"DTLSv1_2 read " s,      \
16677
         "DTLSv1_2 write " s,     \
16678
         "DTLSv1_2 " s},          \
16679
        {"DTLSv1_3 read " s,      \
16680
         "DTLSv1_3 write " s,     \
16681
         "DTLSv1_3 " s},          \
16682
    }
16683
16684
/* Gets the current state of the WOLFSSL structure
16685
 *
16686
 * ssl WOLFSSL structure to get state of
16687
 *
16688
 * Returns a human readable string of the WOLFSSL structure state
16689
 */
16690
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
16691
{
16692
16693
    static const char* OUTPUT_STR[24][8][3] = {
16694
        STATE_STRINGS_PROTO("Initialization"),
16695
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
16696
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
16697
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
16698
        STATE_STRINGS_PROTO_RW("Server Hello"),
16699
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
16700
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
16701
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
16702
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
16703
        STATE_STRINGS_PROTO_RW("Server Cert"),
16704
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
16705
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
16706
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
16707
        STATE_STRINGS_PROTO_RW("Server Finished"),
16708
        STATE_STRINGS_PROTO_RW("server Key Update"),
16709
        STATE_STRINGS_PROTO_RW("Client Hello"),
16710
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
16711
        STATE_STRINGS_PROTO_RW("Client Cert"),
16712
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
16713
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
16714
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
16715
        STATE_STRINGS_PROTO_RW("Client Finished"),
16716
        STATE_STRINGS_PROTO_RW("Client Key Update"),
16717
        STATE_STRINGS_PROTO("Handshake Done"),
16718
    };
16719
    enum ProtocolVer {
16720
        SSL_V3 = 0,
16721
        TLS_V1,
16722
        TLS_V1_1,
16723
        TLS_V1_2,
16724
        TLS_V1_3,
16725
        DTLS_V1,
16726
        DTLS_V1_2,
16727
        DTLS_V1_3,
16728
        UNKNOWN = 100
16729
    };
16730
16731
    enum IOMode {
16732
        SS_READ = 0,
16733
        SS_WRITE,
16734
        SS_NEITHER
16735
    };
16736
16737
    enum SslState {
16738
        ss_null_state = 0,
16739
        ss_server_hellorequest,
16740
        ss_server_helloverify,
16741
        ss_server_helloretryrequest,
16742
        ss_server_hello,
16743
        ss_server_certificatestatus,
16744
        ss_server_encryptedextensions,
16745
        ss_server_sessionticket,
16746
        ss_server_certrequest,
16747
        ss_server_cert,
16748
        ss_server_keyexchange,
16749
        ss_server_hellodone,
16750
        ss_server_changecipherspec,
16751
        ss_server_finished,
16752
        ss_server_keyupdate,
16753
        ss_client_hello,
16754
        ss_client_keyexchange,
16755
        ss_client_cert,
16756
        ss_client_changecipherspec,
16757
        ss_client_certverify,
16758
        ss_client_endofearlydata,
16759
        ss_client_finished,
16760
        ss_client_keyupdate,
16761
        ss_handshake_done
16762
    };
16763
16764
    int protocol = 0;
16765
    int cbmode = 0;
16766
    int state = 0;
16767
16768
    WOLFSSL_ENTER("wolfSSL_state_string_long");
16769
    if (ssl == NULL) {
16770
        WOLFSSL_MSG("Null argument passed in");
16771
        return NULL;
16772
    }
16773
16774
    /* Get state of callback */
16775
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
16776
        cbmode =  SS_WRITE;
16777
    }
16778
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
16779
        cbmode =  SS_READ;
16780
    }
16781
    else {
16782
        cbmode =  SS_NEITHER;
16783
    }
16784
16785
    /* Get protocol version */
16786
    switch (ssl->version.major) {
16787
        case SSLv3_MAJOR:
16788
            switch (ssl->version.minor) {
16789
                case SSLv3_MINOR:
16790
                    protocol = SSL_V3;
16791
                    break;
16792
                case TLSv1_MINOR:
16793
                    protocol = TLS_V1;
16794
                    break;
16795
                case TLSv1_1_MINOR:
16796
                    protocol = TLS_V1_1;
16797
                    break;
16798
                case TLSv1_2_MINOR:
16799
                    protocol = TLS_V1_2;
16800
                    break;
16801
                case TLSv1_3_MINOR:
16802
                    protocol = TLS_V1_3;
16803
                    break;
16804
                default:
16805
                    protocol = UNKNOWN;
16806
            }
16807
            break;
16808
        case DTLS_MAJOR:
16809
            switch (ssl->version.minor) {
16810
                case DTLS_MINOR:
16811
                    protocol = DTLS_V1;
16812
                    break;
16813
                case DTLSv1_2_MINOR:
16814
                    protocol = DTLS_V1_2;
16815
                    break;
16816
                case DTLSv1_3_MINOR:
16817
                    protocol = DTLS_V1_3;
16818
                    break;
16819
                default:
16820
                    protocol = UNKNOWN;
16821
            }
16822
            break;
16823
    default:
16824
        protocol = UNKNOWN;
16825
    }
16826
16827
    /* accept process */
16828
    if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
16829
        state = ssl->cbtype;
16830
        switch (state) {
16831
            case hello_request:
16832
                state = ss_server_hellorequest;
16833
                break;
16834
            case client_hello:
16835
                state = ss_client_hello;
16836
                break;
16837
            case server_hello:
16838
                state = ss_server_hello;
16839
                break;
16840
            case hello_verify_request:
16841
                state = ss_server_helloverify;
16842
                break;
16843
            case session_ticket:
16844
                state = ss_server_sessionticket;
16845
                break;
16846
            case end_of_early_data:
16847
                state = ss_client_endofearlydata;
16848
                break;
16849
            case hello_retry_request:
16850
                state = ss_server_helloretryrequest;
16851
                break;
16852
            case encrypted_extensions:
16853
                state = ss_server_encryptedextensions;
16854
                break;
16855
            case certificate:
16856
                if (ssl->options.side == WOLFSSL_SERVER_END)
16857
                    state = ss_client_cert;
16858
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
16859
                    state = ss_server_cert;
16860
                else {
16861
                    WOLFSSL_MSG("Unknown State");
16862
                    state = ss_null_state;
16863
                }
16864
                break;
16865
            case server_key_exchange:
16866
                state = ss_server_keyexchange;
16867
                break;
16868
            case certificate_request:
16869
                state = ss_server_certrequest;
16870
                break;
16871
            case server_hello_done:
16872
                state = ss_server_hellodone;
16873
                break;
16874
            case certificate_verify:
16875
                state = ss_client_certverify;
16876
                break;
16877
            case client_key_exchange:
16878
                state = ss_client_keyexchange;
16879
                break;
16880
            case finished:
16881
                if (ssl->options.side == WOLFSSL_SERVER_END)
16882
                    state = ss_client_finished;
16883
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
16884
                    state = ss_server_finished;
16885
                else {
16886
                    WOLFSSL_MSG("Unknown State");
16887
                    state = ss_null_state;
16888
                }
16889
                break;
16890
            case certificate_status:
16891
                state = ss_server_certificatestatus;
16892
                break;
16893
            case key_update:
16894
                if (ssl->options.side == WOLFSSL_SERVER_END)
16895
                    state = ss_client_keyupdate;
16896
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
16897
                    state = ss_server_keyupdate;
16898
                else {
16899
                    WOLFSSL_MSG("Unknown State");
16900
                    state = ss_null_state;
16901
                }
16902
                break;
16903
            case change_cipher_hs:
16904
                if (ssl->options.side == WOLFSSL_SERVER_END)
16905
                    state = ss_client_changecipherspec;
16906
                else if (ssl->options.side == WOLFSSL_CLIENT_END)
16907
                    state = ss_server_changecipherspec;
16908
                else {
16909
                    WOLFSSL_MSG("Unknown State");
16910
                    state = ss_null_state;
16911
                }
16912
                break;
16913
            default:
16914
                WOLFSSL_MSG("Unknown State");
16915
                state = ss_null_state;
16916
        }
16917
    }
16918
    else {
16919
        /* Send process */
16920
        if (ssl->options.side == WOLFSSL_SERVER_END)
16921
            state = ssl->options.serverState;
16922
        else
16923
            state = ssl->options.clientState;
16924
16925
        switch (state) {
16926
            case SERVER_HELLOVERIFYREQUEST_COMPLETE:
16927
                state = ss_server_helloverify;
16928
                break;
16929
            case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
16930
                state = ss_server_helloretryrequest;
16931
                break;
16932
            case SERVER_HELLO_COMPLETE:
16933
                state = ss_server_hello;
16934
                break;
16935
            case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
16936
                state = ss_server_encryptedextensions;
16937
                break;
16938
            case SERVER_CERT_COMPLETE:
16939
                state = ss_server_cert;
16940
                break;
16941
            case SERVER_KEYEXCHANGE_COMPLETE:
16942
                state = ss_server_keyexchange;
16943
                break;
16944
            case SERVER_HELLODONE_COMPLETE:
16945
                state = ss_server_hellodone;
16946
                break;
16947
            case SERVER_CHANGECIPHERSPEC_COMPLETE:
16948
                state = ss_server_changecipherspec;
16949
                break;
16950
            case SERVER_FINISHED_COMPLETE:
16951
                state = ss_server_finished;
16952
                break;
16953
            case CLIENT_HELLO_RETRY:
16954
            case CLIENT_HELLO_COMPLETE:
16955
                state = ss_client_hello;
16956
                break;
16957
            case CLIENT_KEYEXCHANGE_COMPLETE:
16958
                state = ss_client_keyexchange;
16959
                break;
16960
            case CLIENT_CHANGECIPHERSPEC_COMPLETE:
16961
                state = ss_client_changecipherspec;
16962
                break;
16963
            case CLIENT_FINISHED_COMPLETE:
16964
                state = ss_client_finished;
16965
                break;
16966
            case HANDSHAKE_DONE:
16967
                state = ss_handshake_done;
16968
                break;
16969
            default:
16970
                WOLFSSL_MSG("Unknown State");
16971
                state = ss_null_state;
16972
        }
16973
    }
16974
16975
    if (protocol == UNKNOWN) {
16976
        WOLFSSL_MSG("Unknown protocol");
16977
        return "";
16978
    }
16979
    else {
16980
        return OUTPUT_STR[state][protocol][cbmode];
16981
    }
16982
}
16983
16984
#endif /* OPENSSL_EXTRA */
16985
16986
static long wolf_set_options(long old_op, long op)
16987
0
{
16988
    /* if SSL_OP_ALL then turn all bug workarounds on */
16989
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
16990
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
16991
0
    }
16992
16993
    /* by default cookie exchange is on with DTLS */
16994
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
16995
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
16996
0
    }
16997
16998
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
16999
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
17000
0
    }
17001
17002
#ifdef SSL_OP_NO_TLSv1_3
17003
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
17004
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
17005
    }
17006
#endif
17007
17008
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
17009
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
17010
0
    }
17011
17012
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
17013
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
17014
0
    }
17015
17016
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
17017
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
17018
0
    }
17019
17020
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
17021
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
17022
0
    }
17023
17024
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
17025
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
17026
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
17027
0
    }
17028
17029
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
17030
    #ifdef HAVE_LIBZ
17031
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
17032
    #else
17033
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
17034
0
    #endif
17035
0
    }
17036
17037
0
    return old_op | op;
17038
0
}
17039
17040
static int FindHashSig(const Suites* suites, byte first, byte second)
17041
0
{
17042
0
    word16 i;
17043
17044
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
17045
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
17046
0
        return SUITES_ERROR;
17047
0
    }
17048
17049
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
17050
0
        if (suites->hashSigAlgo[i]   == first &&
17051
0
            suites->hashSigAlgo[i+1] == second )
17052
0
            return i;
17053
0
    }
17054
17055
0
    return MATCH_SUITE_ERROR;
17056
0
}
17057
17058
long wolfSSL_set_options(WOLFSSL* ssl, long op)
17059
0
{
17060
0
    word16 haveRSA = 1;
17061
0
    word16 havePSK = 0;
17062
0
    int    keySz   = 0;
17063
17064
0
    WOLFSSL_ENTER("wolfSSL_set_options");
17065
17066
0
    if (ssl == NULL) {
17067
0
        return 0;
17068
0
    }
17069
17070
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
17071
17072
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
17073
0
        WOLFSSL_MSG("Disabling TLS 1.3");
17074
0
        if (ssl->version.minor == TLSv1_3_MINOR)
17075
0
            ssl->version.minor = TLSv1_2_MINOR;
17076
0
    }
17077
17078
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
17079
0
        WOLFSSL_MSG("Disabling TLS 1.2");
17080
0
        if (ssl->version.minor == TLSv1_2_MINOR)
17081
0
            ssl->version.minor = TLSv1_1_MINOR;
17082
0
    }
17083
17084
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
17085
0
        WOLFSSL_MSG("Disabling TLS 1.1");
17086
0
        if (ssl->version.minor == TLSv1_1_MINOR)
17087
0
            ssl->version.minor = TLSv1_MINOR;
17088
0
    }
17089
17090
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
17091
0
        WOLFSSL_MSG("Disabling TLS 1.0");
17092
0
        if (ssl->version.minor == TLSv1_MINOR)
17093
0
            ssl->version.minor = SSLv3_MINOR;
17094
0
    }
17095
17096
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
17097
0
        == WOLFSSL_OP_NO_COMPRESSION) {
17098
    #ifdef HAVE_LIBZ
17099
        ssl->options.usingCompression = 0;
17100
    #endif
17101
0
    }
17102
17103
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
17104
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
17105
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
17106
      ssl->options.noTicketTls12 = 1;
17107
    }
17108
#endif
17109
17110
17111
    /* in the case of a version change the cipher suites should be reset */
17112
#ifndef NO_PSK
17113
    havePSK = ssl->options.havePSK;
17114
#endif
17115
#ifdef NO_RSA
17116
    haveRSA = 0;
17117
#endif
17118
0
#ifndef NO_CERTS
17119
0
    keySz = ssl->buffers.keySz;
17120
0
#endif
17121
17122
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
17123
0
        if (AllocateSuites(ssl) != 0)
17124
0
            return 0;
17125
0
        if (!ssl->suites->setSuites) {
17126
0
            InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
17127
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
17128
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17129
0
                       ssl->options.useAnon,
17130
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17131
0
        }
17132
0
        else {
17133
            /* Only preserve overlapping suites */
17134
0
            Suites tmpSuites;
17135
0
            word16 in, out;
17136
0
            word16 haveECDSAsig, haveStaticECC;
17137
#ifdef NO_RSA
17138
            haveECDSAsig = 1;
17139
            haveStaticECC = 1;
17140
#else
17141
0
            haveECDSAsig = 0;
17142
0
            haveStaticECC = ssl->options.haveStaticECC;
17143
0
#endif
17144
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
17145
            /* Get all possible ciphers and sigalgs for the version. Following
17146
             * options limit the allowed ciphers so let's try to get as many as
17147
             * possible.
17148
             * - haveStaticECC turns off haveRSA
17149
             * - haveECDSAsig turns off haveRSAsig */
17150
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
17151
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
17152
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
17153
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
17154
0
                        ssl->suites->suites[in+1]) >= 0) {
17155
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
17156
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
17157
0
                    out += SUITE_LEN;
17158
0
                }
17159
0
            }
17160
0
            ssl->suites->suiteSz = out;
17161
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
17162
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
17163
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
17164
0
                    ssl->suites->hashSigAlgo[out] =
17165
0
                            ssl->suites->hashSigAlgo[in];
17166
0
                    ssl->suites->hashSigAlgo[out+1] =
17167
0
                            ssl->suites->hashSigAlgo[in+1];
17168
0
                    out += 2;
17169
0
                }
17170
0
            }
17171
0
            ssl->suites->hashSigAlgoSz = out;
17172
0
        }
17173
0
    }
17174
17175
0
    return (long)ssl->options.mask;
17176
0
}
17177
17178
17179
long wolfSSL_get_options(const WOLFSSL* ssl)
17180
52.2k
{
17181
52.2k
    WOLFSSL_ENTER("wolfSSL_get_options");
17182
52.2k
    if(ssl == NULL)
17183
0
        return WOLFSSL_FAILURE;
17184
52.2k
    return (long)ssl->options.mask;
17185
52.2k
}
17186
17187
#if defined(HAVE_SECURE_RENEGOTIATION) \
17188
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
17189
/* clears the counter for number of renegotiations done
17190
 * returns the current count before it is cleared */
17191
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
17192
0
{
17193
0
    long total;
17194
17195
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
17196
0
    if (s == NULL)
17197
0
        return 0;
17198
17199
0
    total = s->secure_rene_count;
17200
0
    s->secure_rene_count = 0;
17201
0
    return total;
17202
0
}
17203
17204
17205
/* return the number of renegotiations since wolfSSL_new */
17206
long wolfSSL_total_renegotiations(WOLFSSL *s)
17207
0
{
17208
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
17209
0
    return wolfSSL_num_renegotiations(s);
17210
0
}
17211
17212
17213
/* return the number of renegotiations since wolfSSL_new */
17214
long wolfSSL_num_renegotiations(WOLFSSL* s)
17215
0
{
17216
0
    if (s == NULL) {
17217
0
        return 0;
17218
0
    }
17219
17220
0
    return s->secure_rene_count;
17221
0
}
17222
17223
17224
/* Is there a renegotiation currently in progress? */
17225
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
17226
0
{
17227
0
    return s && s->options.handShakeDone &&
17228
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
17229
0
}
17230
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
17231
17232
#ifdef OPENSSL_EXTRA
17233
17234
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
17235
{
17236
    WOLFSSL_ENTER("wolfSSL_clear_options");
17237
    if(ssl == NULL)
17238
        return WOLFSSL_FAILURE;
17239
    ssl->options.mask &= (unsigned long)~opt;
17240
    return (long)ssl->options.mask;
17241
}
17242
17243
#ifdef HAVE_PK_CALLBACKS
17244
long wolfSSL_set_tlsext_debug_arg(WOLFSSL* ssl, void *arg)
17245
{
17246
    if (ssl == NULL) {
17247
        return WOLFSSL_FAILURE;
17248
    }
17249
17250
    ssl->loggingCtx = arg;
17251
    return WOLFSSL_SUCCESS;
17252
}
17253
#endif /* HAVE_PK_CALLBACKS */
17254
17255
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST
17256
long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type)
17257
{
17258
    WOLFSSL_ENTER("wolfSSL_set_tlsext_status_type");
17259
17260
    if (s == NULL){
17261
        return BAD_FUNC_ARG;
17262
    }
17263
17264
    if (type == WOLFSSL_TLSEXT_STATUSTYPE_ocsp){
17265
        int r = TLSX_UseCertificateStatusRequest(&s->extensions, (byte)type, 0,
17266
            s, s->heap, s->devId);
17267
        return (long)r;
17268
    } else {
17269
        WOLFSSL_MSG(
17270
       "SSL_set_tlsext_status_type only supports TLSEXT_STATUSTYPE_ocsp type.");
17271
        return WOLFSSL_FAILURE;
17272
    }
17273
17274
}
17275
17276
long wolfSSL_get_tlsext_status_type(WOLFSSL *s)
17277
{
17278
    TLSX* extension;
17279
17280
    if (s == NULL)
17281
        return WOLFSSL_FATAL_ERROR;
17282
    extension = TLSX_Find(s->extensions, TLSX_STATUS_REQUEST);
17283
    return extension != NULL ? WOLFSSL_TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR;
17284
}
17285
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
17286
17287
#ifndef NO_WOLFSSL_STUB
17288
long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg)
17289
{
17290
    (void)s;
17291
    (void)arg;
17292
    WOLFSSL_STUB("wolfSSL_get_tlsext_status_exts");
17293
    return WOLFSSL_FAILURE;
17294
}
17295
#endif
17296
17297
/*** TBD ***/
17298
#ifndef NO_WOLFSSL_STUB
17299
long wolfSSL_set_tlsext_status_exts(WOLFSSL *s, void *arg)
17300
{
17301
    (void)s;
17302
    (void)arg;
17303
    WOLFSSL_STUB("wolfSSL_set_tlsext_status_exts");
17304
    return WOLFSSL_FAILURE;
17305
}
17306
#endif
17307
17308
/*** TBD ***/
17309
#ifndef NO_WOLFSSL_STUB
17310
long wolfSSL_get_tlsext_status_ids(WOLFSSL *s, void *arg)
17311
{
17312
    (void)s;
17313
    (void)arg;
17314
    WOLFSSL_STUB("wolfSSL_get_tlsext_status_ids");
17315
    return WOLFSSL_FAILURE;
17316
}
17317
#endif
17318
17319
/*** TBD ***/
17320
#ifndef NO_WOLFSSL_STUB
17321
long wolfSSL_set_tlsext_status_ids(WOLFSSL *s, void *arg)
17322
{
17323
    (void)s;
17324
    (void)arg;
17325
    WOLFSSL_STUB("wolfSSL_set_tlsext_status_ids");
17326
    return WOLFSSL_FAILURE;
17327
}
17328
#endif
17329
17330
#ifndef NO_WOLFSSL_STUB
17331
/*** TBD ***/
17332
WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl)
17333
{
17334
    (void)ssl;
17335
    WOLFSSL_STUB("SSL_get_privatekey");
17336
    return NULL;
17337
}
17338
#endif
17339
17340
#ifndef NO_WOLFSSL_STUB
17341
/*** TBD ***/
17342
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
17343
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
17344
{
17345
    (void)ctx;
17346
    (void)dh;
17347
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
17348
}
17349
#endif
17350
17351
#ifndef NO_WOLFSSL_STUB
17352
/*** TBD ***/
17353
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
17354
{
17355
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
17356
    return NULL;
17357
}
17358
#endif
17359
17360
17361
#if !defined(NETOS)
17362
void wolfSSL_ERR_load_SSL_strings(void)
17363
{
17364
17365
}
17366
#endif
17367
17368
#ifdef HAVE_MAX_FRAGMENT
17369
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
17370
/**
17371
 * Set max fragment tls extension
17372
 * @param c a pointer to WOLFSSL_CTX object
17373
 * @param mode maximum fragment length mode
17374
 * @return 1 on success, otherwise 0 or negative error code
17375
 */
17376
int wolfSSL_CTX_set_tlsext_max_fragment_length(WOLFSSL_CTX *c,
17377
                                               unsigned char mode)
17378
{
17379
    if (c == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
17380
        return BAD_FUNC_ARG;
17381
17382
    return wolfSSL_CTX_UseMaxFragment(c, mode);
17383
}
17384
/**
17385
 * Set max fragment tls extension
17386
 * @param c a pointer to WOLFSSL object
17387
 * @param mode maximum fragment length mode
17388
 * @return 1 on success, otherwise 0 or negative error code
17389
 */
17390
int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s, unsigned char mode)
17391
{
17392
    if (s == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 ))
17393
        return BAD_FUNC_ARG;
17394
17395
    return wolfSSL_UseMaxFragment(s, mode);
17396
}
17397
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
17398
#endif /* HAVE_MAX_FRAGMENT */
17399
17400
#endif /* OPENSSL_EXTRA */
17401
17402
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
17403
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
17404
{
17405
    byte len = 0;
17406
17407
    WOLFSSL_ENTER("wolfSSL_get_finished");
17408
17409
    if (!ssl || !buf || count < TLS_FINISHED_SZ) {
17410
        WOLFSSL_MSG("Bad parameter");
17411
        return WOLFSSL_FAILURE;
17412
    }
17413
17414
    if (ssl->options.side == WOLFSSL_SERVER_END) {
17415
        len = ssl->serverFinished_len;
17416
        XMEMCPY(buf, ssl->serverFinished, len);
17417
    }
17418
    else {
17419
        len = ssl->clientFinished_len;
17420
        XMEMCPY(buf, ssl->clientFinished, len);
17421
    }
17422
    return len;
17423
}
17424
17425
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
17426
{
17427
    byte len = 0;
17428
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
17429
17430
    if (!ssl || !buf || count < TLS_FINISHED_SZ) {
17431
        WOLFSSL_MSG("Bad parameter");
17432
        return WOLFSSL_FAILURE;
17433
    }
17434
17435
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
17436
        len = ssl->serverFinished_len;
17437
        XMEMCPY(buf, ssl->serverFinished, len);
17438
    }
17439
    else {
17440
        len = ssl->clientFinished_len;
17441
        XMEMCPY(buf, ssl->clientFinished, len);
17442
    }
17443
17444
    return len;
17445
}
17446
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
17447
17448
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
17449
    defined(OPENSSL_ALL)
17450
long wolfSSL_get_verify_result(const WOLFSSL *ssl)
17451
{
17452
    if (ssl == NULL) {
17453
        return WOLFSSL_FAILURE;
17454
    }
17455
17456
    return (long)ssl->peerVerifyRet;
17457
}
17458
#endif
17459
17460
#ifdef OPENSSL_EXTRA
17461
17462
#ifndef NO_WOLFSSL_STUB
17463
/* shows the number of accepts attempted by CTX in it's lifetime */
17464
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
17465
{
17466
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
17467
    (void)ctx;
17468
    return 0;
17469
}
17470
#endif
17471
17472
#ifndef NO_WOLFSSL_STUB
17473
/* shows the number of connects attempted CTX in it's lifetime */
17474
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
17475
{
17476
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
17477
    (void)ctx;
17478
    return 0;
17479
}
17480
#endif
17481
17482
17483
#ifndef NO_WOLFSSL_STUB
17484
/* shows the number of accepts completed by CTX in it's lifetime */
17485
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
17486
{
17487
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
17488
    (void)ctx;
17489
    return 0;
17490
}
17491
#endif
17492
17493
17494
#ifndef NO_WOLFSSL_STUB
17495
/* shows the number of connects completed by CTX in it's lifetime */
17496
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
17497
{
17498
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
17499
    (void)ctx;
17500
    return 0;
17501
}
17502
#endif
17503
17504
17505
#ifndef NO_WOLFSSL_STUB
17506
/* shows the number of renegotiation accepts attempted by CTX */
17507
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
17508
{
17509
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
17510
    (void)ctx;
17511
    return 0;
17512
}
17513
#endif
17514
17515
17516
#ifndef NO_WOLFSSL_STUB
17517
/* shows the number of renegotiation accepts attempted by CTX */
17518
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
17519
{
17520
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
17521
    (void)ctx;
17522
    return 0;
17523
}
17524
#endif
17525
17526
17527
#ifndef NO_WOLFSSL_STUB
17528
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
17529
{
17530
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
17531
    (void)ctx;
17532
    return 0;
17533
}
17534
#endif
17535
17536
17537
#ifndef NO_WOLFSSL_STUB
17538
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
17539
{
17540
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
17541
    (void)ctx;
17542
    return 0;
17543
}
17544
#endif
17545
17546
17547
#ifndef NO_WOLFSSL_STUB
17548
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
17549
{
17550
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
17551
    (void)ctx;
17552
    return 0;
17553
}
17554
#endif
17555
17556
17557
#ifndef NO_WOLFSSL_STUB
17558
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
17559
{
17560
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
17561
    (void)ctx;
17562
    return 0;
17563
}
17564
#endif
17565
17566
17567
#ifndef NO_WOLFSSL_STUB
17568
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
17569
{
17570
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
17571
    (void)ctx;
17572
    return 0;
17573
}
17574
#endif
17575
17576
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
17577
{
17578
    if (ssl == NULL) {
17579
        return WOLFSSL_FAILURE;
17580
    }
17581
17582
    return ssl->readAhead;
17583
}
17584
17585
17586
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
17587
{
17588
    if (ssl == NULL) {
17589
        return WOLFSSL_FAILURE;
17590
    }
17591
17592
    ssl->readAhead = (byte)v;
17593
17594
    return WOLFSSL_SUCCESS;
17595
}
17596
17597
17598
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
17599
{
17600
    if (ctx == NULL) {
17601
        return WOLFSSL_FAILURE;
17602
    }
17603
17604
    return ctx->readAhead;
17605
}
17606
17607
17608
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
17609
{
17610
    if (ctx == NULL) {
17611
        return WOLFSSL_FAILURE;
17612
    }
17613
17614
    ctx->readAhead = (byte)v;
17615
17616
    return WOLFSSL_SUCCESS;
17617
}
17618
17619
17620
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
17621
        void* arg)
17622
{
17623
    if (ctx == NULL) {
17624
        return WOLFSSL_FAILURE;
17625
    }
17626
17627
    ctx->userPRFArg = arg;
17628
    return WOLFSSL_SUCCESS;
17629
}
17630
17631
#endif /* OPENSSL_EXTRA */
17632
17633
#if defined(OPENSSL_EXTRA) && defined(KEEP_PEER_CERT) && \
17634
    defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM)
17635
int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname)
17636
{
17637
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
17638
17639
    WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file");
17640
    if (ssl != NULL && fname != NULL)
17641
    {
17642
    #ifdef WOLFSSL_SMALL_STACK
17643
        byte           staticBuffer[1]; /* force heap usage */
17644
    #else
17645
        byte           staticBuffer[FILE_BUFFER_SIZE];
17646
    #endif
17647
        byte*          myBuffer  = staticBuffer;
17648
        int            dynamic   = 0;
17649
        XFILE          file;
17650
        long           sz        = 0;
17651
        WOLFSSL_CTX*   ctx       = ssl->ctx;
17652
        WOLFSSL_X509*  peer_cert = &ssl->peerCert;
17653
        DerBuffer*     fileDer = NULL;
17654
17655
        file = XFOPEN(fname, "rb");
17656
        if (file == XBADFILE)
17657
            return WOLFSSL_BAD_FILE;
17658
17659
        if (XFSEEK(file, 0, XSEEK_END) != 0) {
17660
            XFCLOSE(file);
17661
            return WOLFSSL_BAD_FILE;
17662
        }
17663
        sz = XFTELL(file);
17664
        if (XFSEEK(file, 0, XSEEK_SET) != 0) {
17665
            XFCLOSE(file);
17666
            return WOLFSSL_BAD_FILE;
17667
        }
17668
17669
        if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) {
17670
            WOLFSSL_MSG("cmp_peer_cert_to_file size error");
17671
            XFCLOSE(file);
17672
            return WOLFSSL_BAD_FILE;
17673
        }
17674
17675
        if (sz > (long)sizeof(staticBuffer)) {
17676
            WOLFSSL_MSG("Getting dynamic buffer");
17677
            myBuffer = (byte*)XMALLOC((size_t)sz, ctx->heap, DYNAMIC_TYPE_FILE);
17678
            dynamic = 1;
17679
        }
17680
17681
        if ((myBuffer != NULL) &&
17682
            (sz > 0) &&
17683
            (XFREAD(myBuffer, 1, (size_t)sz, file) == (size_t)sz) &&
17684
            (PemToDer(myBuffer, (long)sz, CERT_TYPE,
17685
                      &fileDer, ctx->heap, NULL, NULL) == 0) &&
17686
            (fileDer->length != 0) &&
17687
            (fileDer->length == peer_cert->derCert->length) &&
17688
            (XMEMCMP(peer_cert->derCert->buffer, fileDer->buffer,
17689
                                                fileDer->length) == 0))
17690
        {
17691
            ret = 0;
17692
        }
17693
17694
        FreeDer(&fileDer);
17695
17696
        if (dynamic)
17697
            XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
17698
17699
        XFCLOSE(file);
17700
    }
17701
17702
    return ret;
17703
}
17704
#endif
17705
17706
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
17707
const WOLFSSL_ObjectInfo wolfssl_object_info[] = {
17708
#ifndef NO_CERTS
17709
    /* oidCertExtType */
17710
    { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType,
17711
      "basicConstraints", "X509v3 Basic Constraints"},
17712
    { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName",
17713
      "X509v3 Subject Alternative Name"},
17714
    { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType,
17715
      "crlDistributionPoints", "X509v3 CRL Distribution Points"},
17716
    { WC_NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess",
17717
      "Authority Information Access"},
17718
    { WC_NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType,
17719
      "authorityKeyIdentifier", "X509v3 Authority Key Identifier"},
17720
    { WC_NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType,
17721
      "subjectKeyIdentifier", "X509v3 Subject Key Identifier"},
17722
    { WC_NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage",
17723
      "X509v3 Key Usage"},
17724
    { WC_NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType,
17725
      "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"},
17726
    { WC_NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType,
17727
      "extendedKeyUsage", "X509v3 Extended Key Usage"},
17728
    { WC_NID_name_constraints, NAME_CONS_OID, oidCertExtType,
17729
      "nameConstraints", "X509v3 Name Constraints"},
17730
    { WC_NID_certificate_policies, CERT_POLICY_OID, oidCertExtType,
17731
      "certificatePolicies", "X509v3 Certificate Policies"},
17732
17733
    /* oidCertAuthInfoType */
17734
    { WC_NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP",
17735
      "OCSP"},
17736
    { WC_NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType,
17737
      "caIssuers", "CA Issuers"},
17738
17739
    /* oidCertPolicyType */
17740
    { WC_NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy",
17741
      "X509v3 Any Policy"},
17742
17743
    /* oidCertAltNameType */
17744
    { WC_NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""},
17745
17746
    /* oidCertKeyUseType */
17747
    { WC_NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType,
17748
      "anyExtendedKeyUsage", "Any Extended Key Usage"},
17749
    { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType,
17750
      "serverAuth", "TLS Web Server Authentication"},
17751
    { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType,
17752
      "clientAuth", "TLS Web Client Authentication"},
17753
    { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType,
17754
      "OCSPSigning", "OCSP Signing"},
17755
17756
    /* oidCertNameType */
17757
    { WC_NID_commonName, WC_NAME_COMMON_NAME_OID, oidCertNameType,
17758
      "CN", "commonName"},
17759
#if !defined(WOLFSSL_CERT_REQ)
17760
    { WC_NID_surname, WC_NAME_SURNAME_OID, oidCertNameType, "SN", "surname"},
17761
#endif
17762
    { WC_NID_serialNumber, WC_NAME_SERIAL_NUMBER_OID, oidCertNameType,
17763
      "serialNumber", "serialNumber"},
17764
    { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"},
17765
    { WC_NID_countryName, WC_NAME_COUNTRY_NAME_OID, oidCertNameType,
17766
      "C", "countryName"},
17767
    { WC_NID_localityName, WC_NAME_LOCALITY_NAME_OID, oidCertNameType,
17768
      "L", "localityName"},
17769
    { WC_NID_stateOrProvinceName, WC_NAME_STATE_NAME_OID, oidCertNameType,
17770
      "ST", "stateOrProvinceName"},
17771
    { WC_NID_streetAddress, WC_NAME_STREET_ADDRESS_OID, oidCertNameType,
17772
      "street", "streetAddress"},
17773
    { WC_NID_organizationName, WC_NAME_ORGANIZATION_NAME_OID, oidCertNameType,
17774
      "O", "organizationName"},
17775
    { WC_NID_organizationalUnitName, WC_NAME_ORGANIZATION_UNIT_NAME_OID,
17776
      oidCertNameType, "OU", "organizationalUnitName"},
17777
    { WC_NID_title, WC_NAME_TITLE_OID, oidCertNameType, "title", "title"},
17778
    { WC_NID_description, WC_NAME_DESCRIPTION_OID, oidCertNameType,
17779
      "description", "description"},
17780
    { WC_NID_emailAddress, WC_NAME_EMAIL_ADDRESS_OID, oidCertNameType,
17781
      "emailAddress", "emailAddress"},
17782
    { WC_NID_domainComponent, WC_NAME_DOMAIN_COMPONENT_OID, oidCertNameType,
17783
      "DC", "domainComponent"},
17784
    { WC_NID_rfc822Mailbox, WC_NAME_RFC822_MAILBOX_OID, oidCertNameType,
17785
      "rfc822Mailbox", "rfc822Mailbox"},
17786
    { WC_NID_favouriteDrink, WC_NAME_FAVOURITE_DRINK_OID, oidCertNameType,
17787
      "favouriteDrink", "favouriteDrink"},
17788
    { WC_NID_businessCategory, WC_NAME_BUSINESS_CATEGORY_OID, oidCertNameType,
17789
      "businessCategory", "businessCategory"},
17790
    { WC_NID_jurisdictionCountryName, WC_NAME_JURIS_COUNTRY_OID,
17791
      oidCertNameType, "jurisdictionC", "jurisdictionCountryName"},
17792
    { WC_NID_jurisdictionStateOrProvinceName, WC_NAME_JURIS_STATE_PROV_OID,
17793
      oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"},
17794
    { WC_NID_postalCode, WC_NAME_POSTAL_CODE_OID, oidCertNameType, "postalCode",
17795
      "postalCode"},
17796
    { WC_NID_userId, WC_NAME_USER_ID_OID, oidCertNameType, "UID", "userId"},
17797
    { WC_NID_netscape_cert_type, NETSCAPE_CT_OID, oidCertNameType,
17798
      "nsCertType", "Netscape Cert Type"},
17799
17800
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL)
17801
    { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID,
17802
            oidCsrAttrType, "challengePassword", "challengePassword"},
17803
    { WC_NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID,
17804
        oidCsrAttrType, "contentType", "contentType" },
17805
    { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID,
17806
        oidCsrAttrType, "unstructuredName", "unstructuredName" },
17807
    { WC_NID_name, WC_NAME_NAME_OID, oidCsrAttrType, "name", "name" },
17808
    { WC_NID_surname, SURNAME_OID,
17809
        oidCsrAttrType, "surname", "surname" },
17810
    { WC_NID_givenName, WC_NAME_GIVEN_NAME_OID,
17811
        oidCsrAttrType, "givenName", "givenName" },
17812
    { WC_NID_initials, WC_NAME_INITIALIS_OID,
17813
        oidCsrAttrType, "initials", "initials" },
17814
    { WC_NID_dnQualifier, DNQUALIFIER_OID,
17815
        oidCsrAttrType, "dnQualifer", "dnQualifier" },
17816
#endif
17817
#endif
17818
#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */
17819
        /* oidHashType */
17820
    #ifdef WOLFSSL_MD2
17821
        { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"},
17822
    #endif
17823
    #ifndef NO_MD4
17824
        { WC_NID_md4, MD4h, oidHashType, "MD4", "md4"},
17825
    #endif
17826
    #ifndef NO_MD5
17827
        { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"},
17828
    #endif
17829
    #ifndef NO_SHA
17830
        { WC_NID_sha1, SHAh, oidHashType, "SHA1", "sha1"},
17831
    #endif
17832
    #ifdef WOLFSSL_SHA224
17833
        { WC_NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"},
17834
    #endif
17835
    #ifndef NO_SHA256
17836
        { WC_NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"},
17837
    #endif
17838
    #ifdef WOLFSSL_SHA384
17839
        { WC_NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"},
17840
    #endif
17841
    #ifdef WOLFSSL_SHA512
17842
        { WC_NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"},
17843
    #endif
17844
    #ifdef WOLFSSL_SHA3
17845
        #ifndef WOLFSSL_NOSHA3_224
17846
        { WC_NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"},
17847
        #endif
17848
        #ifndef WOLFSSL_NOSHA3_256
17849
        { WC_NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"},
17850
        #endif
17851
        #ifndef WOLFSSL_NOSHA3_384
17852
        { WC_NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"},
17853
        #endif
17854
        #ifndef WOLFSSL_NOSHA3_512
17855
        { WC_NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"},
17856
        #endif
17857
    #endif /* WOLFSSL_SHA3 */
17858
    #ifdef WOLFSSL_SM3
17859
        { WC_NID_sm3, SM3h, oidHashType, "SM3", "sm3"},
17860
    #endif
17861
        /* oidSigType */
17862
    #ifndef NO_DSA
17863
        #ifndef NO_SHA
17864
        { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType,
17865
          "DSA-SHA1", "dsaWithSHA1"},
17866
        { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256",
17867
          "dsa_with_SHA256"},
17868
        #endif
17869
    #endif /* NO_DSA */
17870
    #ifndef NO_RSA
17871
        #ifdef WOLFSSL_MD2
17872
        { WC_NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2",
17873
          "md2WithRSAEncryption"},
17874
        #endif
17875
        #ifndef NO_MD5
17876
        { WC_NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5",
17877
          "md5WithRSAEncryption"},
17878
        #endif
17879
        #ifndef NO_SHA
17880
        { WC_NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1",
17881
          "sha1WithRSAEncryption"},
17882
        #endif
17883
        #ifdef WOLFSSL_SHA224
17884
        { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType,
17885
          "RSA-SHA224", "sha224WithRSAEncryption"},
17886
        #endif
17887
        #ifndef NO_SHA256
17888
        { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType,
17889
          "RSA-SHA256", "sha256WithRSAEncryption"},
17890
        #endif
17891
        #ifdef WOLFSSL_SHA384
17892
        { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType,
17893
          "RSA-SHA384", "sha384WithRSAEncryption"},
17894
        #endif
17895
        #ifdef WOLFSSL_SHA512
17896
        { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType,
17897
          "RSA-SHA512", "sha512WithRSAEncryption"},
17898
        #endif
17899
        #ifdef WOLFSSL_SHA3
17900
        #ifndef WOLFSSL_NOSHA3_224
17901
        { WC_NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224",
17902
          "sha3-224WithRSAEncryption"},
17903
        #endif
17904
        #ifndef WOLFSSL_NOSHA3_256
17905
        { WC_NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256",
17906
          "sha3-256WithRSAEncryption"},
17907
        #endif
17908
        #ifndef WOLFSSL_NOSHA3_384
17909
        { WC_NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384",
17910
          "sha3-384WithRSAEncryption"},
17911
        #endif
17912
        #ifndef WOLFSSL_NOSHA3_512
17913
        { WC_NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512",
17914
          "sha3-512WithRSAEncryption"},
17915
        #endif
17916
        #endif
17917
        #ifdef WC_RSA_PSS
17918
        { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType,
17919
          "RSASSA-PSS", "rsassaPss" },
17920
        #endif
17921
    #endif /* NO_RSA */
17922
    #ifdef HAVE_ECC
17923
        #ifndef NO_SHA
17924
        { WC_NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1",
17925
          "shaWithECDSA"},
17926
        #endif
17927
        #ifdef WOLFSSL_SHA224
17928
        { WC_NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType,
17929
          "ecdsa-with-SHA224","sha224WithECDSA"},
17930
        #endif
17931
        #ifndef NO_SHA256
17932
        { WC_NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType,
17933
          "ecdsa-with-SHA256","sha256WithECDSA"},
17934
        #endif
17935
        #ifdef WOLFSSL_SHA384
17936
        { WC_NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType,
17937
          "ecdsa-with-SHA384","sha384WithECDSA"},
17938
        #endif
17939
        #ifdef WOLFSSL_SHA512
17940
        { WC_NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType,
17941
          "ecdsa-with-SHA512","sha512WithECDSA"},
17942
        #endif
17943
        #ifdef WOLFSSL_SHA3
17944
        #ifndef WOLFSSL_NOSHA3_224
17945
        { WC_NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType,
17946
          "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"},
17947
        #endif
17948
        #ifndef WOLFSSL_NOSHA3_256
17949
        { WC_NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType,
17950
          "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"},
17951
        #endif
17952
        #ifndef WOLFSSL_NOSHA3_384
17953
        { WC_NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType,
17954
          "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"},
17955
        #endif
17956
        #ifndef WOLFSSL_NOSHA3_512
17957
        { WC_NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType,
17958
          "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"},
17959
        #endif
17960
        #endif
17961
    #endif /* HAVE_ECC */
17962
17963
        /* oidKeyType */
17964
    #ifndef NO_DSA
17965
        { WC_NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"},
17966
    #endif /* NO_DSA */
17967
    #ifndef NO_RSA
17968
        { WC_NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption",
17969
          "rsaEncryption"},
17970
    #ifdef WC_RSA_PSS
17971
        { WC_NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"},
17972
    #endif
17973
    #endif /* NO_RSA */
17974
    #ifdef HAVE_ECC
17975
        { WC_NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey",
17976
                                                        "id-ecPublicKey"},
17977
    #endif /* HAVE_ECC */
17978
    #ifndef NO_DH
17979
        { WC_NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement",
17980
          "dhKeyAgreement"},
17981
    #endif
17982
    #ifdef HAVE_ED448
17983
        { WC_NID_ED448, ED448k,  oidKeyType, "ED448", "ED448"},
17984
    #endif
17985
    #ifdef HAVE_ED25519
17986
        { WC_NID_ED25519, ED25519k,  oidKeyType, "ED25519", "ED25519"},
17987
    #endif
17988
    #ifdef HAVE_FALCON
17989
        { CTC_FALCON_LEVEL1, FALCON_LEVEL1k,  oidKeyType, "Falcon Level 1",
17990
                                                          "Falcon Level 1"},
17991
        { CTC_FALCON_LEVEL5, FALCON_LEVEL5k,  oidKeyType, "Falcon Level 5",
17992
                                                          "Falcon Level 5"},
17993
    #endif /* HAVE_FALCON */
17994
    #ifdef HAVE_DILITHIUM
17995
    #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT
17996
        { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k,  oidKeyType,
17997
          "Dilithium Level 2", "Dilithium Level 2"},
17998
        { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k,  oidKeyType,
17999
          "Dilithium Level 3", "Dilithium Level 3"},
18000
        { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k,  oidKeyType,
18001
          "Dilithium Level 5", "Dilithium Level 5"},
18002
    #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */
18003
        { CTC_ML_DSA_LEVEL2, ML_DSA_LEVEL2k,  oidKeyType,
18004
          "ML-DSA 44", "ML-DSA 44"},
18005
        { CTC_ML_DSA_LEVEL3, ML_DSA_LEVEL3k,  oidKeyType,
18006
          "ML-DSA 65", "ML-DSA 65"},
18007
        { CTC_ML_DSA_LEVEL5, ML_DSA_LEVEL5k,  oidKeyType,
18008
          "ML-DSA 87", "ML-DSA 87"},
18009
    #endif /* HAVE_DILITHIUM */
18010
18011
        /* oidCurveType */
18012
    #ifdef HAVE_ECC
18013
        { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType,
18014
          "prime192v1", "prime192v1"},
18015
        { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType,
18016
          "prime192v2", "prime192v2"},
18017
        { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType,
18018
          "prime192v3", "prime192v3"},
18019
18020
        { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType,
18021
          "prime239v1", "prime239v1"},
18022
        { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType,
18023
          "prime239v2", "prime239v2"},
18024
        { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType,
18025
          "prime239v3", "prime239v3"},
18026
18027
        { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType,
18028
          "prime256v1", "prime256v1"},
18029
18030
        { WC_NID_secp112r1, ECC_SECP112R1_OID,  oidCurveType, "secp112r1",
18031
          "secp112r1"},
18032
        { WC_NID_secp112r2, ECC_SECP112R2_OID,  oidCurveType, "secp112r2",
18033
          "secp112r2"},
18034
18035
        { WC_NID_secp128r1, ECC_SECP128R1_OID,  oidCurveType, "secp128r1",
18036
          "secp128r1"},
18037
        { WC_NID_secp128r2, ECC_SECP128R2_OID,  oidCurveType, "secp128r2",
18038
          "secp128r2"},
18039
18040
        { WC_NID_secp160r1, ECC_SECP160R1_OID,  oidCurveType, "secp160r1",
18041
          "secp160r1"},
18042
        { WC_NID_secp160r2, ECC_SECP160R2_OID,  oidCurveType, "secp160r2",
18043
          "secp160r2"},
18044
18045
        { WC_NID_secp224r1, ECC_SECP224R1_OID,  oidCurveType, "secp224r1",
18046
          "secp224r1"},
18047
        { WC_NID_secp384r1, ECC_SECP384R1_OID,  oidCurveType, "secp384r1",
18048
          "secp384r1"},
18049
        { WC_NID_secp521r1, ECC_SECP521R1_OID,  oidCurveType, "secp521r1",
18050
          "secp521r1"},
18051
18052
        { WC_NID_secp160k1, ECC_SECP160K1_OID,  oidCurveType, "secp160k1",
18053
          "secp160k1"},
18054
        { WC_NID_secp192k1, ECC_SECP192K1_OID,  oidCurveType, "secp192k1",
18055
          "secp192k1"},
18056
        { WC_NID_secp224k1, ECC_SECP224K1_OID,  oidCurveType, "secp224k1",
18057
          "secp224k1"},
18058
        { WC_NID_secp256k1, ECC_SECP256K1_OID,  oidCurveType, "secp256k1",
18059
          "secp256k1"},
18060
18061
        { WC_NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID,  oidCurveType,
18062
          "brainpoolP160r1", "brainpoolP160r1"},
18063
        { WC_NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID,  oidCurveType,
18064
          "brainpoolP192r1", "brainpoolP192r1"},
18065
        { WC_NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID,  oidCurveType,
18066
          "brainpoolP224r1", "brainpoolP224r1"},
18067
        { WC_NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID,  oidCurveType,
18068
          "brainpoolP256r1", "brainpoolP256r1"},
18069
        { WC_NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID,  oidCurveType,
18070
          "brainpoolP320r1", "brainpoolP320r1"},
18071
        { WC_NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID,  oidCurveType,
18072
          "brainpoolP384r1", "brainpoolP384r1"},
18073
        { WC_NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID,  oidCurveType,
18074
          "brainpoolP512r1", "brainpoolP512r1"},
18075
18076
    #ifdef WOLFSSL_SM2
18077
        { WC_NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"},
18078
    #endif
18079
    #endif /* HAVE_ECC */
18080
18081
        /* oidBlkType */
18082
    #ifdef WOLFSSL_AES_128
18083
        { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"},
18084
    #endif
18085
    #ifdef WOLFSSL_AES_192
18086
        { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"},
18087
    #endif
18088
    #ifdef WOLFSSL_AES_256
18089
        { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"},
18090
    #endif
18091
    #ifndef NO_DES3
18092
        { WC_NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"},
18093
        { WC_NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"},
18094
    #endif /* !NO_DES3 */
18095
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
18096
        { WC_NID_chacha20_poly1305, WC_NID_chacha20_poly1305, oidBlkType,
18097
          "ChaCha20-Poly1305", "chacha20-poly1305"},
18098
    #endif
18099
18100
        /* oidOcspType */
18101
    #ifdef HAVE_OCSP
18102
        { WC_NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType,
18103
          "basicOCSPResponse", "Basic OCSP Response"},
18104
        { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"},
18105
    #endif /* HAVE_OCSP */
18106
18107
    #ifndef NO_PWDBASED
18108
        /* oidKdfType */
18109
        { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"},
18110
18111
        /* oidPBEType */
18112
        { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType,
18113
          "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"},
18114
        { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES",
18115
          "pbeWithSHA1AndDES-CBC"},
18116
        { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES",
18117
          "pbeWithSHA1And3-KeyTripleDES-CBC"},
18118
    #endif
18119
18120
        /* oidKeyWrapType */
18121
    #ifdef WOLFSSL_AES_128
18122
        { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap",
18123
          "aes128-wrap"},
18124
    #endif
18125
    #ifdef WOLFSSL_AES_192
18126
        { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap",
18127
          "aes192-wrap"},
18128
    #endif
18129
    #ifdef WOLFSSL_AES_256
18130
        { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap",
18131
          "aes256-wrap"},
18132
    #endif
18133
18134
    #ifndef NO_PKCS7
18135
        #ifndef NO_DH
18136
        /* oidCmsKeyAgreeType */
18137
            #ifndef NO_SHA
18138
        { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme,
18139
          oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme",
18140
          "dhSinglePass-stdDH-sha1kdf-scheme"},
18141
            #endif
18142
            #ifdef WOLFSSL_SHA224
18143
        { dhSinglePass_stdDH_sha224kdf_scheme,
18144
          dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType,
18145
          "dhSinglePass-stdDH-sha224kdf-scheme",
18146
          "dhSinglePass-stdDH-sha224kdf-scheme"},
18147
            #endif
18148
            #ifndef NO_SHA256
18149
        { dhSinglePass_stdDH_sha256kdf_scheme,
18150
          dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType,
18151
          "dhSinglePass-stdDH-sha256kdf-scheme",
18152
          "dhSinglePass-stdDH-sha256kdf-scheme"},
18153
            #endif
18154
            #ifdef WOLFSSL_SHA384
18155
        { dhSinglePass_stdDH_sha384kdf_scheme,
18156
          dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType,
18157
          "dhSinglePass-stdDH-sha384kdf-scheme",
18158
          "dhSinglePass-stdDH-sha384kdf-scheme"},
18159
            #endif
18160
            #ifdef WOLFSSL_SHA512
18161
        { dhSinglePass_stdDH_sha512kdf_scheme,
18162
          dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType,
18163
          "dhSinglePass-stdDH-sha512kdf-scheme",
18164
          "dhSinglePass-stdDH-sha512kdf-scheme"},
18165
            #endif
18166
        #endif
18167
    #endif
18168
    #if defined(WOLFSSL_APACHE_HTTPD)
18169
        /* "1.3.6.1.5.5.7.8.7" */
18170
        { WC_NID_id_on_dnsSRV, WOLFSSL_DNS_SRV_SUM, oidCertNameType,
18171
            WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV },
18172
18173
        /* "1.3.6.1.4.1.311.20.2.3" */
18174
        { WC_NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN,
18175
            WOLFSSL_LN_MS_UPN },
18176
18177
        /* "1.3.6.1.5.5.7.1.24" */
18178
        { WC_NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType,
18179
            WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE },
18180
    #endif
18181
#endif /* OPENSSL_EXTRA */
18182
};
18183
18184
#define WOLFSSL_OBJECT_INFO_SZ \
18185
                (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info))
18186
const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ;
18187
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
18188
18189
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
18190
/* Free the dynamically allocated data.
18191
 *
18192
 * p  Pointer to dynamically allocated memory.
18193
 */
18194
void wolfSSL_OPENSSL_free(void* p)
18195
{
18196
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
18197
18198
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
18199
}
18200
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
18201
18202
#ifdef OPENSSL_EXTRA
18203
18204
void *wolfSSL_OPENSSL_malloc(size_t a)
18205
{
18206
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
18207
}
18208
18209
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
18210
{
18211
    /* 'char' is unsigned on some platforms. */
18212
    return (int)(signed char)HexCharToByte((char)c);
18213
}
18214
18215
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
18216
{
18217
    unsigned char* targetBuf;
18218
    int srcDigitHigh = 0;
18219
    int srcDigitLow = 0;
18220
    size_t srcLen;
18221
    size_t srcIdx = 0;
18222
    long targetIdx = 0;
18223
18224
    srcLen = XSTRLEN(str);
18225
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
18226
    if (targetBuf == NULL) {
18227
        return NULL;
18228
    }
18229
18230
    while (srcIdx < srcLen) {
18231
        if (str[srcIdx] == ':') {
18232
            srcIdx++;
18233
            continue;
18234
        }
18235
18236
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
18237
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
18238
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
18239
            WOLFSSL_MSG("Invalid hex character.");
18240
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
18241
            return NULL;
18242
        }
18243
18244
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
18245
                                                  srcDigitLow       );
18246
    }
18247
18248
    if (len != NULL)
18249
        *len = targetIdx;
18250
18251
    return targetBuf;
18252
}
18253
18254
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
18255
{
18256
    (void)opts;
18257
    (void)settings;
18258
    return wolfSSL_library_init();
18259
}
18260
18261
int wolfSSL_OPENSSL_init_crypto(word64 opts,
18262
    const WOLFSSL_INIT_SETTINGS* settings)
18263
{
18264
    (void)opts;
18265
    (void)settings;
18266
    return wolfSSL_library_init();
18267
}
18268
18269
/* Colon separated list of <public key>+<digest> algorithms.
18270
 * Replaces list in context.
18271
 */
18272
int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list)
18273
{
18274
    WOLFSSL_MSG("wolfSSL_CTX_set1_sigalg_list");
18275
18276
    if (ctx == NULL || list == NULL) {
18277
        WOLFSSL_MSG("Bad function arguments");
18278
        return WOLFSSL_FAILURE;
18279
    }
18280
18281
    if (AllocateCtxSuites(ctx) != 0)
18282
        return WOLFSSL_FAILURE;
18283
18284
    return SetSuitesHashSigAlgo(ctx->suites, list);
18285
}
18286
18287
/* Colon separated list of <public key>+<digest> algorithms.
18288
 * Replaces list in SSL.
18289
 */
18290
int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list)
18291
{
18292
    WOLFSSL_MSG("wolfSSL_set1_sigalg_list");
18293
18294
    if (ssl == NULL || list == NULL) {
18295
        WOLFSSL_MSG("Bad function arguments");
18296
        return WOLFSSL_FAILURE;
18297
    }
18298
18299
    if (AllocateSuites(ssl) != 0)
18300
        return WOLFSSL_FAILURE;
18301
18302
    return SetSuitesHashSigAlgo(ssl->suites, list);
18303
}
18304
18305
static int HashToNid(byte hashAlgo, int* nid)
18306
{
18307
    int ret = WOLFSSL_SUCCESS;
18308
18309
    /* Cast for compiler to check everything is implemented */
18310
    switch ((enum wc_MACAlgorithm)hashAlgo) {
18311
        case no_mac:
18312
        case rmd_mac:
18313
            *nid = WC_NID_undef;
18314
            break;
18315
        case md5_mac:
18316
            *nid = WC_NID_md5;
18317
            break;
18318
        case sha_mac:
18319
            *nid = WC_NID_sha1;
18320
            break;
18321
        case sha224_mac:
18322
            *nid = WC_NID_sha224;
18323
            break;
18324
        case sha256_mac:
18325
            *nid = WC_NID_sha256;
18326
            break;
18327
        case sha384_mac:
18328
            *nid = WC_NID_sha384;
18329
            break;
18330
        case sha512_mac:
18331
            *nid = WC_NID_sha512;
18332
            break;
18333
        case blake2b_mac:
18334
            *nid = WC_NID_blake2b512;
18335
            break;
18336
        case sm3_mac:
18337
            *nid = WC_NID_sm3;
18338
            break;
18339
        default:
18340
            ret = WOLFSSL_FAILURE;
18341
            break;
18342
    }
18343
18344
    return ret;
18345
}
18346
18347
static int SaToNid(byte sa, int* nid)
18348
{
18349
    int ret = WOLFSSL_SUCCESS;
18350
    /* Cast for compiler to check everything is implemented */
18351
    switch ((enum SignatureAlgorithm)sa) {
18352
        case anonymous_sa_algo:
18353
            *nid = WC_NID_undef;
18354
            break;
18355
        case rsa_sa_algo:
18356
            *nid = WC_NID_rsaEncryption;
18357
            break;
18358
        case dsa_sa_algo:
18359
            *nid = WC_NID_dsa;
18360
            break;
18361
        case ecc_dsa_sa_algo:
18362
            *nid = WC_NID_X9_62_id_ecPublicKey;
18363
            break;
18364
        case rsa_pss_sa_algo:
18365
            *nid = WC_NID_rsassaPss;
18366
            break;
18367
        case ed25519_sa_algo:
18368
#ifdef HAVE_ED25519
18369
            *nid = WC_NID_ED25519;
18370
#else
18371
            ret = WOLFSSL_FAILURE;
18372
#endif
18373
            break;
18374
        case rsa_pss_pss_algo:
18375
            *nid = WC_NID_rsassaPss;
18376
            break;
18377
        case ed448_sa_algo:
18378
#ifdef HAVE_ED448
18379
            *nid = WC_NID_ED448;
18380
#else
18381
            ret = WOLFSSL_FAILURE;
18382
#endif
18383
            break;
18384
        case falcon_level1_sa_algo:
18385
            *nid = CTC_FALCON_LEVEL1;
18386
            break;
18387
        case falcon_level5_sa_algo:
18388
            *nid = CTC_FALCON_LEVEL5;
18389
            break;
18390
        case dilithium_level2_sa_algo:
18391
            *nid = CTC_ML_DSA_LEVEL2;
18392
            break;
18393
        case dilithium_level3_sa_algo:
18394
            *nid = CTC_ML_DSA_LEVEL3;
18395
            break;
18396
        case dilithium_level5_sa_algo:
18397
            *nid = CTC_ML_DSA_LEVEL5;
18398
            break;
18399
        case sm2_sa_algo:
18400
            *nid = WC_NID_sm2;
18401
            break;
18402
        case invalid_sa_algo:
18403
        case any_sa_algo:
18404
        default:
18405
            ret = WOLFSSL_FAILURE;
18406
            break;
18407
    }
18408
    return ret;
18409
}
18410
18411
/* This API returns the hash selected. */
18412
int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid)
18413
{
18414
    WOLFSSL_MSG("wolfSSL_get_signature_nid");
18415
18416
    if (ssl == NULL || nid == NULL) {
18417
        WOLFSSL_MSG("Bad function arguments");
18418
        return WOLFSSL_FAILURE;
18419
    }
18420
18421
    return HashToNid(ssl->options.hashAlgo, nid);
18422
}
18423
18424
/* This API returns the signature selected. */
18425
int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid)
18426
{
18427
    WOLFSSL_MSG("wolfSSL_get_signature_type_nid");
18428
18429
    if (ssl == NULL || nid == NULL) {
18430
        WOLFSSL_MSG("Bad function arguments");
18431
        return WOLFSSL_FAILURE;
18432
    }
18433
18434
    return SaToNid(ssl->options.sigAlgo, nid);
18435
}
18436
18437
int wolfSSL_get_peer_signature_nid(WOLFSSL* ssl, int* nid)
18438
{
18439
    WOLFSSL_MSG("wolfSSL_get_peer_signature_nid");
18440
18441
    if (ssl == NULL || nid == NULL) {
18442
        WOLFSSL_MSG("Bad function arguments");
18443
        return WOLFSSL_FAILURE;
18444
    }
18445
18446
    return HashToNid(ssl->options.peerHashAlgo, nid);
18447
}
18448
18449
int wolfSSL_get_peer_signature_type_nid(const WOLFSSL* ssl, int* nid)
18450
{
18451
    WOLFSSL_MSG("wolfSSL_get_peer_signature_type_nid");
18452
18453
    if (ssl == NULL || nid == NULL) {
18454
        WOLFSSL_MSG("Bad function arguments");
18455
        return WOLFSSL_FAILURE;
18456
    }
18457
18458
    return SaToNid(ssl->options.peerSigAlgo, nid);
18459
}
18460
18461
#ifdef HAVE_ECC
18462
18463
#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
18464
int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list)
18465
{
18466
    if (!ctx || !list) {
18467
        return WOLFSSL_FAILURE;
18468
    }
18469
18470
    return set_curves_list(NULL, ctx, list, 0);
18471
}
18472
18473
int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list)
18474
{
18475
    if (!ssl || !list) {
18476
        return WOLFSSL_FAILURE;
18477
    }
18478
18479
    return set_curves_list(ssl, NULL, list, 0);
18480
}
18481
#endif /* WOLFSSL_TLS13 */
18482
18483
#endif /* HAVE_ECC */
18484
18485
#endif /* OPENSSL_EXTRA */
18486
18487
#ifdef WOLFSSL_ALT_CERT_CHAINS
18488
int wolfSSL_is_peer_alt_cert_chain(const WOLFSSL* ssl)
18489
{
18490
    int isUsing = 0;
18491
    if (ssl)
18492
        isUsing = ssl->options.usingAltCertChain;
18493
    return isUsing;
18494
}
18495
#endif /* WOLFSSL_ALT_CERT_CHAINS */
18496
18497
18498
#ifdef SESSION_CERTS
18499
18500
#ifdef WOLFSSL_ALT_CERT_CHAINS
18501
/* Get peer's alternate certificate chain */
18502
WOLFSSL_X509_CHAIN* wolfSSL_get_peer_alt_chain(WOLFSSL* ssl)
18503
{
18504
    WOLFSSL_ENTER("wolfSSL_get_peer_alt_chain");
18505
    if (ssl)
18506
        return &ssl->session->altChain;
18507
18508
    return 0;
18509
}
18510
#endif /* WOLFSSL_ALT_CERT_CHAINS */
18511
18512
18513
/* Get peer's certificate chain */
18514
WOLFSSL_X509_CHAIN* wolfSSL_get_peer_chain(WOLFSSL* ssl)
18515
{
18516
    WOLFSSL_ENTER("wolfSSL_get_peer_chain");
18517
    if (ssl)
18518
        return &ssl->session->chain;
18519
18520
    return 0;
18521
}
18522
18523
18524
/* Get peer's certificate chain total count */
18525
int wolfSSL_get_chain_count(WOLFSSL_X509_CHAIN* chain)
18526
{
18527
    WOLFSSL_ENTER("wolfSSL_get_chain_count");
18528
    if (chain)
18529
        return chain->count;
18530
18531
    return 0;
18532
}
18533
18534
18535
/* Get peer's ASN.1 DER certificate at index (idx) length in bytes */
18536
int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx)
18537
{
18538
    WOLFSSL_ENTER("wolfSSL_get_chain_length");
18539
    if (chain)
18540
        return chain->certs[idx].length;
18541
18542
    return 0;
18543
}
18544
18545
18546
/* Get peer's ASN.1 DER certificate at index (idx) */
18547
byte* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx)
18548
{
18549
    WOLFSSL_ENTER("wolfSSL_get_chain_cert");
18550
    if (chain)
18551
        return chain->certs[idx].buffer;
18552
18553
    return 0;
18554
}
18555
18556
18557
/* Get peer's wolfSSL X509 certificate at index (idx) */
18558
WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx)
18559
{
18560
    int          ret = 0;
18561
    WOLFSSL_X509* x509 = NULL;
18562
    WC_DECLARE_VAR(cert, DecodedCert, 1, 0);
18563
18564
    WOLFSSL_ENTER("wolfSSL_get_chain_X509");
18565
    if (chain != NULL && idx < MAX_CHAIN_DEPTH) {
18566
    #ifdef WOLFSSL_SMALL_STACK
18567
        cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
18568
                                                       DYNAMIC_TYPE_DCERT);
18569
        if (cert != NULL)
18570
    #endif
18571
        {
18572
            InitDecodedCert(cert, chain->certs[idx].buffer,
18573
                                  (word32)chain->certs[idx].length, NULL);
18574
18575
            if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) != 0) {
18576
                WOLFSSL_MSG("Failed to parse cert");
18577
            }
18578
            else {
18579
                x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL,
18580
                                                             DYNAMIC_TYPE_X509);
18581
                if (x509 == NULL) {
18582
                    WOLFSSL_MSG("Failed alloc X509");
18583
                }
18584
                else {
18585
                    InitX509(x509, 1, NULL);
18586
18587
                    if ((ret = CopyDecodedToX509(x509, cert)) != 0) {
18588
                        WOLFSSL_MSG("Failed to copy decoded");
18589
                        wolfSSL_X509_free(x509);
18590
                        x509 = NULL;
18591
                    }
18592
                }
18593
            }
18594
18595
            FreeDecodedCert(cert);
18596
            WC_FREE_VAR_EX(cert, NULL, DYNAMIC_TYPE_DCERT);
18597
        }
18598
    }
18599
    (void)ret;
18600
18601
    return x509;
18602
}
18603
18604
18605
/* Get peer's PEM certificate at index (idx), output to buffer if inLen big
18606
   enough else return error (-1). If buffer is NULL only calculate
18607
   outLen. Output length is in *outLen WOLFSSL_SUCCESS on ok */
18608
int  wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx,
18609
                               unsigned char* buf, int inLen, int* outLen)
18610
{
18611
#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
18612
    const char* header = NULL;
18613
    const char* footer = NULL;
18614
    int headerLen;
18615
    int footerLen;
18616
    int i;
18617
    int err;
18618
    word32 szNeeded = 0;
18619
18620
    WOLFSSL_ENTER("wolfSSL_get_chain_cert_pem");
18621
    if (!chain || !outLen || idx < 0 || idx >= wolfSSL_get_chain_count(chain))
18622
        return BAD_FUNC_ARG;
18623
18624
    err = wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer);
18625
    if (err != 0)
18626
        return err;
18627
18628
    headerLen = (int)XSTRLEN(header);
18629
    footerLen = (int)XSTRLEN(footer);
18630
18631
    /* Null output buffer return size needed in outLen */
18632
    if(!buf) {
18633
        if(Base64_Encode(chain->certs[idx].buffer,
18634
                    (word32)chain->certs[idx].length,
18635
                    NULL, &szNeeded) != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
18636
            return WOLFSSL_FAILURE;
18637
        *outLen = (int)szNeeded + headerLen + footerLen;
18638
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
18639
    }
18640
18641
    /* don't even try if inLen too short */
18642
    if (inLen < headerLen + footerLen + chain->certs[idx].length)
18643
        return BAD_FUNC_ARG;
18644
18645
    /* header */
18646
    if (XMEMCPY(buf, header, (size_t)headerLen) == NULL)
18647
        return WOLFSSL_FATAL_ERROR;
18648
18649
    i = headerLen;
18650
18651
    /* body */
18652
    *outLen = inLen;  /* input to Base64_Encode */
18653
    if ( (err = Base64_Encode(chain->certs[idx].buffer,
18654
                       (word32)chain->certs[idx].length, buf + i,
18655
                       (word32*)outLen)) < 0)
18656
        return err;
18657
    i += *outLen;
18658
18659
    /* footer */
18660
    if ( (i + footerLen) > inLen)
18661
        return BAD_FUNC_ARG;
18662
    if (XMEMCPY(buf + i, footer, (size_t)footerLen) == NULL)
18663
        return WOLFSSL_FATAL_ERROR;
18664
    *outLen += headerLen + footerLen;
18665
18666
    return WOLFSSL_SUCCESS;
18667
#else
18668
    (void)chain;
18669
    (void)idx;
18670
    (void)buf;
18671
    (void)inLen;
18672
    (void)outLen;
18673
    return WOLFSSL_FAILURE;
18674
#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
18675
}
18676
18677
#endif /* SESSION_CERTS */
18678
18679
#ifdef HAVE_FUZZER
18680
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
18681
{
18682
    if (ssl) {
18683
        ssl->fuzzerCb  = cbf;
18684
        ssl->fuzzerCtx = fCtx;
18685
    }
18686
}
18687
#endif
18688
18689
#ifndef NO_CERTS
18690
#ifdef  HAVE_PK_CALLBACKS
18691
18692
#ifdef HAVE_ECC
18693
void  wolfSSL_CTX_SetEccKeyGenCb(WOLFSSL_CTX* ctx, CallbackEccKeyGen cb)
18694
{
18695
    if (ctx)
18696
        ctx->EccKeyGenCb = cb;
18697
}
18698
void  wolfSSL_SetEccKeyGenCtx(WOLFSSL* ssl, void *ctx)
18699
{
18700
    if (ssl)
18701
        ssl->EccKeyGenCtx = ctx;
18702
}
18703
void* wolfSSL_GetEccKeyGenCtx(WOLFSSL* ssl)
18704
{
18705
    if (ssl)
18706
        return ssl->EccKeyGenCtx;
18707
18708
    return NULL;
18709
}
18710
void  wolfSSL_CTX_SetEccSignCtx(WOLFSSL_CTX* ctx, void *userCtx)
18711
{
18712
    if (ctx)
18713
        ctx->EccSignCtx = userCtx;
18714
}
18715
void* wolfSSL_CTX_GetEccSignCtx(WOLFSSL_CTX* ctx)
18716
{
18717
    if (ctx)
18718
        return ctx->EccSignCtx;
18719
18720
    return NULL;
18721
}
18722
18723
WOLFSSL_ABI
18724
void  wolfSSL_CTX_SetEccSignCb(WOLFSSL_CTX* ctx, CallbackEccSign cb)
18725
{
18726
    if (ctx)
18727
        ctx->EccSignCb = cb;
18728
}
18729
void  wolfSSL_SetEccSignCtx(WOLFSSL* ssl, void *ctx)
18730
{
18731
    if (ssl)
18732
        ssl->EccSignCtx = ctx;
18733
}
18734
void* wolfSSL_GetEccSignCtx(WOLFSSL* ssl)
18735
{
18736
    if (ssl)
18737
        return ssl->EccSignCtx;
18738
18739
    return NULL;
18740
}
18741
18742
void  wolfSSL_CTX_SetEccVerifyCb(WOLFSSL_CTX* ctx, CallbackEccVerify cb)
18743
{
18744
    if (ctx)
18745
        ctx->EccVerifyCb = cb;
18746
}
18747
void  wolfSSL_SetEccVerifyCtx(WOLFSSL* ssl, void *ctx)
18748
{
18749
    if (ssl)
18750
        ssl->EccVerifyCtx = ctx;
18751
}
18752
void* wolfSSL_GetEccVerifyCtx(WOLFSSL* ssl)
18753
{
18754
    if (ssl)
18755
        return ssl->EccVerifyCtx;
18756
18757
    return NULL;
18758
}
18759
18760
void wolfSSL_CTX_SetEccSharedSecretCb(WOLFSSL_CTX* ctx,
18761
    CallbackEccSharedSecret cb)
18762
{
18763
    if (ctx)
18764
        ctx->EccSharedSecretCb = cb;
18765
}
18766
void  wolfSSL_SetEccSharedSecretCtx(WOLFSSL* ssl, void *ctx)
18767
{
18768
    if (ssl)
18769
        ssl->EccSharedSecretCtx = ctx;
18770
}
18771
void* wolfSSL_GetEccSharedSecretCtx(WOLFSSL* ssl)
18772
{
18773
    if (ssl)
18774
        return ssl->EccSharedSecretCtx;
18775
18776
    return NULL;
18777
}
18778
#endif /* HAVE_ECC */
18779
18780
#ifdef HAVE_ED25519
18781
void  wolfSSL_CTX_SetEd25519SignCb(WOLFSSL_CTX* ctx, CallbackEd25519Sign cb)
18782
{
18783
    if (ctx)
18784
        ctx->Ed25519SignCb = cb;
18785
}
18786
void  wolfSSL_SetEd25519SignCtx(WOLFSSL* ssl, void *ctx)
18787
{
18788
    if (ssl)
18789
        ssl->Ed25519SignCtx = ctx;
18790
}
18791
void* wolfSSL_GetEd25519SignCtx(WOLFSSL* ssl)
18792
{
18793
    if (ssl)
18794
        return ssl->Ed25519SignCtx;
18795
18796
    return NULL;
18797
}
18798
18799
void  wolfSSL_CTX_SetEd25519VerifyCb(WOLFSSL_CTX* ctx, CallbackEd25519Verify cb)
18800
{
18801
    if (ctx)
18802
        ctx->Ed25519VerifyCb = cb;
18803
}
18804
void  wolfSSL_SetEd25519VerifyCtx(WOLFSSL* ssl, void *ctx)
18805
{
18806
    if (ssl)
18807
        ssl->Ed25519VerifyCtx = ctx;
18808
}
18809
void* wolfSSL_GetEd25519VerifyCtx(WOLFSSL* ssl)
18810
{
18811
    if (ssl)
18812
        return ssl->Ed25519VerifyCtx;
18813
18814
    return NULL;
18815
}
18816
#endif /* HAVE_ED25519 */
18817
18818
#ifdef HAVE_CURVE25519
18819
void wolfSSL_CTX_SetX25519KeyGenCb(WOLFSSL_CTX* ctx,
18820
        CallbackX25519KeyGen cb)
18821
{
18822
    if (ctx)
18823
        ctx->X25519KeyGenCb = cb;
18824
}
18825
void  wolfSSL_SetX25519KeyGenCtx(WOLFSSL* ssl, void *ctx)
18826
{
18827
    if (ssl)
18828
        ssl->X25519KeyGenCtx = ctx;
18829
}
18830
void* wolfSSL_GetX25519KeyGenCtx(WOLFSSL* ssl)
18831
{
18832
    if (ssl)
18833
        return ssl->X25519KeyGenCtx;
18834
18835
    return NULL;
18836
}
18837
18838
void wolfSSL_CTX_SetX25519SharedSecretCb(WOLFSSL_CTX* ctx,
18839
        CallbackX25519SharedSecret cb)
18840
{
18841
    if (ctx)
18842
        ctx->X25519SharedSecretCb = cb;
18843
}
18844
void  wolfSSL_SetX25519SharedSecretCtx(WOLFSSL* ssl, void *ctx)
18845
{
18846
    if (ssl)
18847
        ssl->X25519SharedSecretCtx = ctx;
18848
}
18849
void* wolfSSL_GetX25519SharedSecretCtx(WOLFSSL* ssl)
18850
{
18851
    if (ssl)
18852
        return ssl->X25519SharedSecretCtx;
18853
18854
    return NULL;
18855
}
18856
#endif /* HAVE_CURVE25519 */
18857
18858
#ifdef HAVE_ED448
18859
void  wolfSSL_CTX_SetEd448SignCb(WOLFSSL_CTX* ctx, CallbackEd448Sign cb)
18860
{
18861
    if (ctx)
18862
        ctx->Ed448SignCb = cb;
18863
}
18864
void  wolfSSL_SetEd448SignCtx(WOLFSSL* ssl, void *ctx)
18865
{
18866
    if (ssl)
18867
        ssl->Ed448SignCtx = ctx;
18868
}
18869
void* wolfSSL_GetEd448SignCtx(WOLFSSL* ssl)
18870
{
18871
    if (ssl)
18872
        return ssl->Ed448SignCtx;
18873
18874
    return NULL;
18875
}
18876
18877
void  wolfSSL_CTX_SetEd448VerifyCb(WOLFSSL_CTX* ctx, CallbackEd448Verify cb)
18878
{
18879
    if (ctx)
18880
        ctx->Ed448VerifyCb = cb;
18881
}
18882
void  wolfSSL_SetEd448VerifyCtx(WOLFSSL* ssl, void *ctx)
18883
{
18884
    if (ssl)
18885
        ssl->Ed448VerifyCtx = ctx;
18886
}
18887
void* wolfSSL_GetEd448VerifyCtx(WOLFSSL* ssl)
18888
{
18889
    if (ssl)
18890
        return ssl->Ed448VerifyCtx;
18891
18892
    return NULL;
18893
}
18894
#endif /* HAVE_ED448 */
18895
18896
#ifdef HAVE_CURVE448
18897
void wolfSSL_CTX_SetX448KeyGenCb(WOLFSSL_CTX* ctx,
18898
        CallbackX448KeyGen cb)
18899
{
18900
    if (ctx)
18901
        ctx->X448KeyGenCb = cb;
18902
}
18903
void  wolfSSL_SetX448KeyGenCtx(WOLFSSL* ssl, void *ctx)
18904
{
18905
    if (ssl)
18906
        ssl->X448KeyGenCtx = ctx;
18907
}
18908
void* wolfSSL_GetX448KeyGenCtx(WOLFSSL* ssl)
18909
{
18910
    if (ssl)
18911
        return ssl->X448KeyGenCtx;
18912
18913
    return NULL;
18914
}
18915
18916
void wolfSSL_CTX_SetX448SharedSecretCb(WOLFSSL_CTX* ctx,
18917
        CallbackX448SharedSecret cb)
18918
{
18919
    if (ctx)
18920
        ctx->X448SharedSecretCb = cb;
18921
}
18922
void  wolfSSL_SetX448SharedSecretCtx(WOLFSSL* ssl, void *ctx)
18923
{
18924
    if (ssl)
18925
        ssl->X448SharedSecretCtx = ctx;
18926
}
18927
void* wolfSSL_GetX448SharedSecretCtx(WOLFSSL* ssl)
18928
{
18929
    if (ssl)
18930
        return ssl->X448SharedSecretCtx;
18931
18932
    return NULL;
18933
}
18934
#endif /* HAVE_CURVE448 */
18935
18936
#ifndef NO_RSA
18937
void  wolfSSL_CTX_SetRsaSignCb(WOLFSSL_CTX* ctx, CallbackRsaSign cb)
18938
{
18939
    if (ctx)
18940
        ctx->RsaSignCb = cb;
18941
}
18942
void  wolfSSL_CTX_SetRsaSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb)
18943
{
18944
    if (ctx)
18945
        ctx->RsaSignCheckCb = cb;
18946
}
18947
void  wolfSSL_SetRsaSignCtx(WOLFSSL* ssl, void *ctx)
18948
{
18949
    if (ssl)
18950
        ssl->RsaSignCtx = ctx;
18951
}
18952
void* wolfSSL_GetRsaSignCtx(WOLFSSL* ssl)
18953
{
18954
    if (ssl)
18955
        return ssl->RsaSignCtx;
18956
18957
    return NULL;
18958
}
18959
18960
18961
void  wolfSSL_CTX_SetRsaVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb)
18962
{
18963
    if (ctx)
18964
        ctx->RsaVerifyCb = cb;
18965
}
18966
void  wolfSSL_SetRsaVerifyCtx(WOLFSSL* ssl, void *ctx)
18967
{
18968
    if (ssl)
18969
        ssl->RsaVerifyCtx = ctx;
18970
}
18971
void* wolfSSL_GetRsaVerifyCtx(WOLFSSL* ssl)
18972
{
18973
    if (ssl)
18974
        return ssl->RsaVerifyCtx;
18975
18976
    return NULL;
18977
}
18978
18979
#ifdef WC_RSA_PSS
18980
void  wolfSSL_CTX_SetRsaPssSignCb(WOLFSSL_CTX* ctx, CallbackRsaPssSign cb)
18981
{
18982
    if (ctx)
18983
        ctx->RsaPssSignCb = cb;
18984
}
18985
void  wolfSSL_CTX_SetRsaPssSignCheckCb(WOLFSSL_CTX* ctx,
18986
    CallbackRsaPssVerify cb)
18987
{
18988
    if (ctx)
18989
        ctx->RsaPssSignCheckCb = cb;
18990
}
18991
void  wolfSSL_SetRsaPssSignCtx(WOLFSSL* ssl, void *ctx)
18992
{
18993
    if (ssl)
18994
        ssl->RsaPssSignCtx = ctx;
18995
}
18996
void* wolfSSL_GetRsaPssSignCtx(WOLFSSL* ssl)
18997
{
18998
    if (ssl)
18999
        return ssl->RsaPssSignCtx;
19000
19001
    return NULL;
19002
}
19003
19004
void  wolfSSL_CTX_SetRsaPssVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb)
19005
{
19006
    if (ctx)
19007
        ctx->RsaPssVerifyCb = cb;
19008
}
19009
void  wolfSSL_SetRsaPssVerifyCtx(WOLFSSL* ssl, void *ctx)
19010
{
19011
    if (ssl)
19012
        ssl->RsaPssVerifyCtx = ctx;
19013
}
19014
void* wolfSSL_GetRsaPssVerifyCtx(WOLFSSL* ssl)
19015
{
19016
    if (ssl)
19017
        return ssl->RsaPssVerifyCtx;
19018
19019
    return NULL;
19020
}
19021
#endif /* WC_RSA_PSS */
19022
19023
void  wolfSSL_CTX_SetRsaEncCb(WOLFSSL_CTX* ctx, CallbackRsaEnc cb)
19024
{
19025
    if (ctx)
19026
        ctx->RsaEncCb = cb;
19027
}
19028
void  wolfSSL_SetRsaEncCtx(WOLFSSL* ssl, void *ctx)
19029
{
19030
    if (ssl)
19031
        ssl->RsaEncCtx = ctx;
19032
}
19033
void* wolfSSL_GetRsaEncCtx(WOLFSSL* ssl)
19034
{
19035
    if (ssl)
19036
        return ssl->RsaEncCtx;
19037
19038
    return NULL;
19039
}
19040
19041
void  wolfSSL_CTX_SetRsaDecCb(WOLFSSL_CTX* ctx, CallbackRsaDec cb)
19042
{
19043
    if (ctx)
19044
        ctx->RsaDecCb = cb;
19045
}
19046
void  wolfSSL_SetRsaDecCtx(WOLFSSL* ssl, void *ctx)
19047
{
19048
    if (ssl)
19049
        ssl->RsaDecCtx = ctx;
19050
}
19051
void* wolfSSL_GetRsaDecCtx(WOLFSSL* ssl)
19052
{
19053
    if (ssl)
19054
        return ssl->RsaDecCtx;
19055
19056
    return NULL;
19057
}
19058
#endif /* NO_RSA */
19059
19060
/* callback for premaster secret generation */
19061
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
19062
{
19063
    if (ctx)
19064
        ctx->GenPreMasterCb = cb;
19065
}
19066
/* Set premaster secret generation callback context */
19067
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
19068
{
19069
    if (ssl)
19070
        ssl->GenPreMasterCtx = ctx;
19071
}
19072
/* Get premaster secret generation callback context */
19073
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
19074
{
19075
    if (ssl)
19076
        return ssl->GenPreMasterCtx;
19077
19078
    return NULL;
19079
}
19080
19081
/* callback for master secret generation */
19082
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
19083
    CallbackGenMasterSecret cb)
19084
{
19085
    if (ctx)
19086
        ctx->GenMasterCb = cb;
19087
}
19088
/* Set master secret generation callback context */
19089
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
19090
{
19091
    if (ssl)
19092
        ssl->GenMasterCtx = ctx;
19093
}
19094
/* Get master secret generation callback context */
19095
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
19096
{
19097
    if (ssl)
19098
        return ssl->GenMasterCtx;
19099
19100
    return NULL;
19101
}
19102
19103
/* callback for extended master secret generation */
19104
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
19105
    CallbackGenExtMasterSecret cb)
19106
{
19107
    if (ctx)
19108
        ctx->GenExtMasterCb = cb;
19109
}
19110
/* Set extended master secret generation callback context */
19111
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
19112
{
19113
    if (ssl)
19114
        ssl->GenExtMasterCtx = ctx;
19115
}
19116
/* Get extended master secret generation callback context */
19117
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
19118
{
19119
    if (ssl)
19120
        return ssl->GenExtMasterCtx;
19121
19122
    return NULL;
19123
}
19124
19125
19126
/* callback for session key generation */
19127
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
19128
{
19129
    if (ctx)
19130
        ctx->GenSessionKeyCb = cb;
19131
}
19132
/* Set session key generation callback context */
19133
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
19134
{
19135
    if (ssl)
19136
        ssl->GenSessionKeyCtx = ctx;
19137
}
19138
/* Get session key generation callback context */
19139
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
19140
{
19141
    if (ssl)
19142
        return ssl->GenSessionKeyCtx;
19143
19144
    return NULL;
19145
}
19146
19147
/* callback for setting encryption keys */
19148
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
19149
{
19150
    if (ctx)
19151
        ctx->EncryptKeysCb = cb;
19152
}
19153
/* Set encryption keys callback context */
19154
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
19155
{
19156
    if (ssl)
19157
        ssl->EncryptKeysCtx = ctx;
19158
}
19159
/* Get encryption keys callback context */
19160
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
19161
{
19162
    if (ssl)
19163
        return ssl->EncryptKeysCtx;
19164
19165
    return NULL;
19166
}
19167
19168
/* callback for Tls finished */
19169
/* the callback can be used to build TLS Finished message if enabled */
19170
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
19171
{
19172
    if (ctx)
19173
        ctx->TlsFinishedCb = cb;
19174
}
19175
/* Set Tls finished callback context */
19176
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
19177
{
19178
    if (ssl)
19179
        ssl->TlsFinishedCtx = ctx;
19180
}
19181
/* Get Tls finished callback context */
19182
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
19183
{
19184
    if (ssl)
19185
        return ssl->TlsFinishedCtx;
19186
19187
    return NULL;
19188
}
19189
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
19190
/* callback for verify data */
19191
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
19192
{
19193
    if (ctx)
19194
        ctx->VerifyMacCb = cb;
19195
}
19196
19197
/* Set set keys callback context */
19198
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
19199
{
19200
    if (ssl)
19201
        ssl->VerifyMacCtx = ctx;
19202
}
19203
/* Get set  keys callback context */
19204
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
19205
{
19206
    if (ssl)
19207
        return ssl->VerifyMacCtx;
19208
19209
    return NULL;
19210
}
19211
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
19212
19213
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
19214
                                      CallbackHKDFExpandLabel cb)
19215
{
19216
    if (ctx)
19217
        ctx->HKDFExpandLabelCb = cb;
19218
}
19219
#ifdef WOLFSSL_PUBLIC_ASN
19220
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
19221
                                        CallbackProcessPeerCert cb)
19222
{
19223
    if (ctx)
19224
        ctx->ProcessPeerCertCb = cb;
19225
}
19226
#endif /* WOLFSSL_PUBLIC_ASN */
19227
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
19228
                                       CallbackProcessServerSigKex cb)
19229
{
19230
    if (ctx)
19231
        ctx->ProcessServerSigKexCb = cb;
19232
}
19233
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
19234
                                          CallbackPerformTlsRecordProcessing cb)
19235
{
19236
    if (ctx)
19237
        ctx->PerformTlsRecordProcessingCb = cb;
19238
}
19239
#endif /* HAVE_PK_CALLBACKS */
19240
#endif /* NO_CERTS */
19241
19242
#if defined(HAVE_PK_CALLBACKS) && !defined(NO_DH)
19243
void wolfSSL_CTX_SetDhGenerateKeyPair(WOLFSSL_CTX* ctx,
19244
                                      CallbackDhGenerateKeyPair cb) {
19245
    if (ctx)
19246
        ctx->DhGenerateKeyPairCb = cb;
19247
}
19248
void wolfSSL_CTX_SetDhAgreeCb(WOLFSSL_CTX* ctx, CallbackDhAgree cb)
19249
{
19250
    if (ctx)
19251
        ctx->DhAgreeCb = cb;
19252
}
19253
void wolfSSL_SetDhAgreeCtx(WOLFSSL* ssl, void *ctx)
19254
{
19255
    if (ssl)
19256
        ssl->DhAgreeCtx = ctx;
19257
}
19258
void* wolfSSL_GetDhAgreeCtx(WOLFSSL* ssl)
19259
{
19260
    if (ssl)
19261
        return ssl->DhAgreeCtx;
19262
19263
    return NULL;
19264
}
19265
#endif /* HAVE_PK_CALLBACKS && !NO_DH */
19266
19267
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
19268
19269
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
19270
{
19271
    if (ctx)
19272
        ctx->HkdfExtractCb = cb;
19273
}
19274
19275
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
19276
{
19277
    if (ssl)
19278
        ssl->HkdfExtractCtx = ctx;
19279
}
19280
19281
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
19282
{
19283
    if (ssl)
19284
        return ssl->HkdfExtractCtx;
19285
19286
    return NULL;
19287
}
19288
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
19289
19290
#ifdef WOLFSSL_HAVE_WOLFSCEP
19291
    /* Used by autoconf to see if wolfSCEP is available */
19292
    void wolfSSL_wolfSCEP(void) {}
19293
#endif
19294
19295
19296
#ifdef WOLFSSL_HAVE_CERT_SERVICE
19297
    /* Used by autoconf to see if cert service is available */
19298
    void wolfSSL_cert_service(void) {}
19299
#endif
19300
19301
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
19302
    !defined(WOLFCRYPT_ONLY)
19303
19304
    /* NID variables are dependent on compatibility header files currently
19305
     *
19306
     * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL
19307
     *         on fail
19308
     */
19309
19310
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id)
19311
    {
19312
        return wolfSSL_OBJ_nid2obj_ex(id, NULL);
19313
    }
19314
19315
19316
    WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id,
19317
                                                WOLFSSL_ASN1_OBJECT* arg_obj)
19318
    {
19319
        word32 oidSz = 0;
19320
        int nid = 0;
19321
        const byte* oid;
19322
        word32 type = 0;
19323
        WOLFSSL_ASN1_OBJECT* obj = arg_obj;
19324
        byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */
19325
        word32 objSz = 0;
19326
        const char* sName = NULL;
19327
        int i;
19328
19329
#ifdef WOLFSSL_DEBUG_OPENSSL
19330
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj");
19331
#endif
19332
19333
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
19334
            if (wolfssl_object_info[i].nid == id) {
19335
                nid = id;
19336
                id = wolfssl_object_info[i].id;
19337
                sName = wolfssl_object_info[i].sName;
19338
                type = wolfssl_object_info[i].type;
19339
                break;
19340
            }
19341
        }
19342
        if (i == (int)WOLFSSL_OBJECT_INFO_SZ) {
19343
            WOLFSSL_MSG("NID not in table");
19344
        #ifdef WOLFSSL_QT
19345
            sName = NULL;
19346
            type = (word32)id;
19347
        #else
19348
            return NULL;
19349
        #endif
19350
        }
19351
19352
    #ifdef HAVE_ECC
19353
         if (type == 0 && wc_ecc_get_oid((word32)id, &oid, &oidSz) > 0) {
19354
             type = oidCurveType;
19355
         }
19356
    #endif /* HAVE_ECC */
19357
19358
        if (sName != NULL) {
19359
            if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) {
19360
                WOLFSSL_MSG("Attempted short name is too large");
19361
                return NULL;
19362
            }
19363
        }
19364
19365
        oid = OidFromId((word32)id, type, &oidSz);
19366
19367
        /* set object ID to buffer */
19368
        if (obj == NULL){
19369
            obj = wolfSSL_ASN1_OBJECT_new();
19370
            if (obj == NULL) {
19371
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
19372
                return NULL;
19373
            }
19374
        }
19375
        obj->nid     = nid;
19376
        obj->type    = id;
19377
        obj->grp     = (int)type;
19378
19379
        obj->sName[0] = '\0';
19380
        if (sName != NULL) {
19381
            XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName));
19382
        }
19383
19384
        objBuf[0] = ASN_OBJECT_ID; objSz++;
19385
        objSz += SetLength(oidSz, objBuf + 1);
19386
        if (oidSz) {
19387
            XMEMCPY(objBuf + objSz, oid, oidSz);
19388
            objSz     += oidSz;
19389
        }
19390
19391
        if (obj->objSz == 0 || objSz != obj->objSz) {
19392
            obj->objSz = objSz;
19393
            if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) ||
19394
                                                           (obj->obj == NULL)) {
19395
                if (obj->obj != NULL)
19396
                    XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1);
19397
                obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1);
19398
                if (obj->obj == NULL) {
19399
                    wolfSSL_ASN1_OBJECT_free(obj);
19400
                    return NULL;
19401
                }
19402
                obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
19403
            }
19404
            else {
19405
                obj->dynamic &= (unsigned char)~WOLFSSL_ASN1_DYNAMIC_DATA;
19406
            }
19407
        }
19408
        XMEMCPY((byte*)obj->obj, objBuf, obj->objSz);
19409
19410
        (void)type;
19411
19412
        return obj;
19413
    }
19414
19415
    static const char* oid_translate_num_to_str(const char* oid)
19416
    {
19417
        const struct oid_dict {
19418
            const char* num;
19419
            const char* desc;
19420
        } oid_dict[] = {
19421
            { "2.5.29.37.0",       "Any Extended Key Usage" },
19422
            { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" },
19423
            { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" },
19424
            { "1.3.6.1.5.5.7.3.3", "Code Signing" },
19425
            { "1.3.6.1.5.5.7.3.4", "E-mail Protection" },
19426
            { "1.3.6.1.5.5.7.3.8", "Time Stamping" },
19427
            { "1.3.6.1.5.5.7.3.9", "OCSP Signing" },
19428
            { NULL, NULL }
19429
        };
19430
        const struct oid_dict* idx;
19431
19432
        for (idx = oid_dict; idx->num != NULL; idx++) {
19433
            if (!XSTRCMP(oid, idx->num)) {
19434
                return idx->desc;
19435
            }
19436
        }
19437
        return NULL;
19438
    }
19439
19440
    static int wolfssl_obj2txt_numeric(char *buf, int bufLen,
19441
                                       const WOLFSSL_ASN1_OBJECT *a)
19442
    {
19443
        int bufSz;
19444
        int    length;
19445
        word32 idx = 0;
19446
        byte   tag;
19447
19448
        if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) {
19449
            return WOLFSSL_FAILURE;
19450
        }
19451
19452
        if (tag != ASN_OBJECT_ID) {
19453
            WOLFSSL_MSG("Bad ASN1 Object");
19454
            return WOLFSSL_FAILURE;
19455
        }
19456
19457
        if (GetLength((const byte*)a->obj, &idx, &length,
19458
                       a->objSz) < 0 || length < 0) {
19459
            return ASN_PARSE_E;
19460
        }
19461
19462
        if (bufLen < MAX_OID_STRING_SZ) {
19463
            bufSz = bufLen - 1;
19464
        }
19465
        else {
19466
            bufSz = MAX_OID_STRING_SZ;
19467
        }
19468
19469
        if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx,
19470
                    (word32)length)) <= 0) {
19471
            WOLFSSL_MSG("Error decoding OID");
19472
            return WOLFSSL_FAILURE;
19473
        }
19474
19475
        buf[bufSz] = '\0';
19476
19477
        return bufSz;
19478
    }
19479
19480
    /* If no_name is one then use numerical form, otherwise short name.
19481
     *
19482
     * Returns the buffer size on success, WOLFSSL_FAILURE on error
19483
     */
19484
    int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a,
19485
                            int no_name)
19486
    {
19487
        int bufSz;
19488
        const char* desc;
19489
        const char* name;
19490
19491
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt");
19492
19493
        if (buf == NULL || bufLen <= 1 || a == NULL) {
19494
            WOLFSSL_MSG("Bad input argument");
19495
            return WOLFSSL_FAILURE;
19496
        }
19497
19498
        if (no_name == 1) {
19499
            return wolfssl_obj2txt_numeric(buf, bufLen, a);
19500
        }
19501
19502
        /* return long name unless using x509small, then return short name */
19503
#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA)
19504
        name = a->sName;
19505
#else
19506
        name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a));
19507
#endif
19508
19509
        if (name == NULL) {
19510
            WOLFSSL_MSG("Name not found");
19511
            bufSz = 0;
19512
        }
19513
        else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) {
19514
            bufSz = (int)XSTRLEN(name);
19515
        }
19516
        else {
19517
            bufSz = bufLen - 1;
19518
        }
19519
        if (bufSz) {
19520
            XMEMCPY(buf, name, (size_t)bufSz);
19521
        }
19522
        else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL ||
19523
                 a->type == WOLFSSL_GEN_URI) {
19524
            bufSz = (int)XSTRLEN((const char*)a->obj);
19525
            XMEMCPY(buf, a->obj, min((word32)bufSz, (word32)bufLen));
19526
        }
19527
        else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) {
19528
            if ((desc = oid_translate_num_to_str(buf))) {
19529
                bufSz = (int)XSTRLEN(desc);
19530
                bufSz = (int)min((word32)bufSz,(word32) bufLen - 1);
19531
                XMEMCPY(buf, desc, (size_t)bufSz);
19532
            }
19533
        }
19534
        else {
19535
            bufSz = 0;
19536
        }
19537
19538
        buf[bufSz] = '\0';
19539
19540
        return bufSz;
19541
    }
19542
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
19543
19544
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
19545
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
19546
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
19547
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL)
19548
    /* Returns the long name that corresponds with an ASN1_OBJECT nid value.
19549
     *  n : NID value of ASN1_OBJECT to search */
19550
    const char* wolfSSL_OBJ_nid2ln(int n)
19551
    {
19552
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
19553
        size_t i;
19554
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln");
19555
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
19556
            if (obj_info->nid == n) {
19557
                return obj_info->lName;
19558
            }
19559
        }
19560
        WOLFSSL_MSG("NID not found in table");
19561
        return NULL;
19562
    }
19563
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
19564
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */
19565
19566
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
19567
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
19568
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
19569
    defined(WOLFSSL_HAPROXY)
19570
    /* Return the corresponding short name for the nid <n>.
19571
     * or NULL if short name can't be found.
19572
     */
19573
    const char * wolfSSL_OBJ_nid2sn(int n) {
19574
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
19575
        size_t i;
19576
        WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn");
19577
19578
        if (n == WC_NID_md5) {
19579
            /* WC_NID_surname == WC_NID_md5 and WC_NID_surname comes before WC_NID_md5 in
19580
             * wolfssl_object_info. As a result, the loop below will incorrectly
19581
             * return "SN" instead of "MD5." WC_NID_surname isn't the true OpenSSL
19582
             * NID, but other functions rely on this table and modifying it to
19583
             * conform with OpenSSL's NIDs isn't trivial. */
19584
             return "MD5";
19585
        }
19586
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
19587
            if (obj_info->nid == n) {
19588
                return obj_info->sName;
19589
            }
19590
        }
19591
        WOLFSSL_MSG_EX("SN not found (nid:%d)",n);
19592
        return NULL;
19593
    }
19594
19595
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
19596
    int wolfSSL_OBJ_sn2nid(const char *sn) {
19597
        WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid");
19598
        if (sn == NULL)
19599
            return WC_NID_undef;
19600
        return wc_OBJ_sn2nid(sn);
19601
    }
19602
#endif
19603
19604
    size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o)
19605
    {
19606
        size_t ret = 0;
19607
        int err = 0;
19608
        word32 idx = 0;
19609
        int len = 0;
19610
19611
        WOLFSSL_ENTER("wolfSSL_OBJ_length");
19612
19613
        if (o == NULL || o->obj == NULL) {
19614
            WOLFSSL_MSG("Bad argument.");
19615
            err = 1;
19616
        }
19617
19618
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
19619
            WOLFSSL_MSG("Error parsing ASN.1 header.");
19620
            err = 1;
19621
        }
19622
        if (err == 0) {
19623
            ret = (size_t)len;
19624
        }
19625
19626
        WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret);
19627
19628
        return ret;
19629
    }
19630
19631
    const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o)
19632
    {
19633
        const unsigned char* ret = NULL;
19634
        int err = 0;
19635
        word32 idx = 0;
19636
        int len = 0;
19637
19638
        WOLFSSL_ENTER("wolfSSL_OBJ_get0_data");
19639
19640
        if (o == NULL || o->obj == NULL) {
19641
            WOLFSSL_MSG("Bad argument.");
19642
            err = 1;
19643
        }
19644
19645
        if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) {
19646
            WOLFSSL_MSG("Error parsing ASN.1 header.");
19647
            err = 1;
19648
        }
19649
        if (err == 0) {
19650
            ret = o->obj + idx;
19651
        }
19652
19653
        return ret;
19654
    }
19655
19656
19657
    /* Gets the NID value that corresponds with the ASN1 object.
19658
     *
19659
     * o ASN1 object to get NID of
19660
     *
19661
     * Return NID on success and a negative value on failure
19662
     */
19663
    int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o)
19664
    {
19665
        word32 oid = 0;
19666
        word32 idx = 0;
19667
        int ret;
19668
19669
#ifdef WOLFSSL_DEBUG_OPENSSL
19670
        WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid");
19671
#endif
19672
19673
        if (o == NULL) {
19674
            return WOLFSSL_FATAL_ERROR;
19675
        }
19676
19677
        #ifdef WOLFSSL_QT
19678
        if (o->grp == oidCertExtType) {
19679
            /* If nid is an unknown extension, return WC_NID_undef */
19680
            if (wolfSSL_OBJ_nid2sn(o->nid) == NULL)
19681
                return WC_NID_undef;
19682
        }
19683
        #endif
19684
19685
        if (o->nid > 0)
19686
            return o->nid;
19687
        if ((ret = GetObjectId(o->obj, &idx, &oid,
19688
                                    (word32)o->grp, o->objSz)) < 0) {
19689
            if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) {
19690
                /* Put ASN object tag in front and try again */
19691
                int len = SetObjectId((int)o->objSz, NULL) + (int)o->objSz;
19692
                byte* buf = (byte*)XMALLOC((size_t)len, NULL,
19693
                                            DYNAMIC_TYPE_TMP_BUFFER);
19694
                if (!buf) {
19695
                    WOLFSSL_MSG("malloc error");
19696
                    return WOLFSSL_FATAL_ERROR;
19697
                }
19698
                idx = (word32)SetObjectId((int)o->objSz, buf);
19699
                XMEMCPY(buf + idx, o->obj, o->objSz);
19700
                idx = 0;
19701
                ret = GetObjectId(buf, &idx, &oid, (word32)o->grp, (word32)len);
19702
                XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
19703
                if (ret < 0) {
19704
                    WOLFSSL_MSG("Issue getting OID of object");
19705
                    return WOLFSSL_FATAL_ERROR;
19706
                }
19707
            }
19708
            else {
19709
                WOLFSSL_MSG("Issue getting OID of object");
19710
                return WOLFSSL_FATAL_ERROR;
19711
            }
19712
        }
19713
19714
        return oid2nid(oid, o->grp);
19715
    }
19716
19717
    /* Return the corresponding NID for the long name <ln>
19718
     * or WC_NID_undef if NID can't be found.
19719
     */
19720
    int wolfSSL_OBJ_ln2nid(const char *ln)
19721
    {
19722
        const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info;
19723
        size_t lnlen;
19724
        WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid");
19725
        if (ln && (lnlen = XSTRLEN(ln)) > 0) {
19726
            /* Accept input like "/commonName=" */
19727
            if (ln[0] == '/') {
19728
                ln++;
19729
                lnlen--;
19730
            }
19731
            if (lnlen) {
19732
                size_t i;
19733
19734
                if (ln[lnlen-1] == '=') {
19735
                    lnlen--;
19736
                }
19737
                for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) {
19738
                    if (lnlen == XSTRLEN(obj_info->lName) &&
19739
                            XSTRNCMP(ln, obj_info->lName, lnlen) == 0) {
19740
                        return obj_info->nid;
19741
                    }
19742
                }
19743
            }
19744
        }
19745
        return WC_NID_undef;
19746
    }
19747
19748
    /* compares two objects, return 0 if equal */
19749
    int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a,
19750
                        const WOLFSSL_ASN1_OBJECT* b)
19751
    {
19752
        WOLFSSL_ENTER("wolfSSL_OBJ_cmp");
19753
19754
        if (a && b && a->obj && b->obj) {
19755
            if (a->objSz == b->objSz) {
19756
                return XMEMCMP(a->obj, b->obj, a->objSz);
19757
            }
19758
            else if (a->type == EXT_KEY_USAGE_OID ||
19759
                     b->type == EXT_KEY_USAGE_OID) {
19760
                /* Special case for EXT_KEY_USAGE_OID so that
19761
                 * cmp will be treated as a substring search */
19762
                /* Used in libest to check for id-kp-cmcRA in
19763
                 * EXT_KEY_USAGE extension */
19764
                unsigned int idx;
19765
                const byte* s; /* shorter */
19766
                unsigned int sLen;
19767
                const byte* l; /* longer */
19768
                unsigned int lLen;
19769
                if (a->objSz > b->objSz) {
19770
                    s = b->obj; sLen = b->objSz;
19771
                    l = a->obj; lLen = a->objSz;
19772
                }
19773
                else {
19774
                    s = a->obj; sLen = a->objSz;
19775
                    l = b->obj; lLen = b->objSz;
19776
                }
19777
                for (idx = 0; idx <= lLen - sLen; idx++) {
19778
                    if (XMEMCMP(l + idx, s, sLen) == 0) {
19779
                        /* Found substring */
19780
                        return 0;
19781
                    }
19782
                }
19783
            }
19784
        }
19785
19786
        return WOLFSSL_FATAL_ERROR;
19787
    }
19788
#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL,
19789
          WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */
19790
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
19791
    defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
19792
    defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
19793
    defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY)
19794
    /* Gets the NID value that is related to the OID string passed in. Example
19795
     * string would be "2.5.29.14" for subject key ID.
19796
     *
19797
     * returns NID value on success and WC_NID_undef on error
19798
     */
19799
    int wolfSSL_OBJ_txt2nid(const char* s)
19800
    {
19801
        unsigned int i;
19802
    #ifdef WOLFSSL_CERT_EXT
19803
        int ret;
19804
        unsigned int sum = 0;
19805
        unsigned int outSz = MAX_OID_SZ;
19806
        unsigned char out[MAX_OID_SZ];
19807
19808
        XMEMSET(out, 0, sizeof(out));
19809
    #endif
19810
19811
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid");
19812
19813
        if (s == NULL) {
19814
            return WC_NID_undef;
19815
        }
19816
19817
    #ifdef WOLFSSL_CERT_EXT
19818
        ret = EncodePolicyOID(out, &outSz, s, NULL);
19819
        if (ret == 0) {
19820
            /* sum OID */
19821
            sum = wc_oid_sum(out, outSz);
19822
        }
19823
    #endif /* WOLFSSL_CERT_EXT */
19824
19825
        /* get the group that the OID's sum is in
19826
         * @TODO possible conflict with multiples */
19827
        for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
19828
            int len;
19829
        #ifdef WOLFSSL_CERT_EXT
19830
            if (ret == 0) {
19831
                if (wolfssl_object_info[i].id == (int)sum) {
19832
                    return wolfssl_object_info[i].nid;
19833
                }
19834
            }
19835
        #endif
19836
19837
            /* try as a short name */
19838
            len = (int)XSTRLEN(s);
19839
            if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len &&
19840
                XSTRNCMP(wolfssl_object_info[i].sName, s, (word32)len) == 0) {
19841
                return wolfssl_object_info[i].nid;
19842
            }
19843
19844
            /* try as a long name */
19845
            if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len &&
19846
                XSTRNCMP(wolfssl_object_info[i].lName, s, (word32)len) == 0) {
19847
                return wolfssl_object_info[i].nid;
19848
            }
19849
        }
19850
19851
        return WC_NID_undef;
19852
    }
19853
#endif
19854
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
19855
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
19856
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
19857
    defined(WOLFSSL_HAPROXY)
19858
19859
    /* Creates new ASN1_OBJECT from short name, long name, or text
19860
     * representation of oid. If no_name is 0, then short name, long name, and
19861
     * numerical value of oid are interpreted. If no_name is 1, then only the
19862
     * numerical value of the oid is interpreted.
19863
     *
19864
     * Returns pointer to ASN1_OBJECT on success, or NULL on error.
19865
     */
19866
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
19867
    WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name)
19868
    {
19869
        int i, ret;
19870
        int nid = WC_NID_undef;
19871
        unsigned int outSz = MAX_OID_SZ;
19872
        unsigned char out[MAX_OID_SZ];
19873
        WOLFSSL_ASN1_OBJECT* obj;
19874
19875
        WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj");
19876
19877
        if (s == NULL)
19878
            return NULL;
19879
19880
        /* If s is numerical value, try to sum oid */
19881
        ret = EncodePolicyOID(out, &outSz, s, NULL);
19882
        if (ret == 0 && outSz > 0) {
19883
            /* If numerical encode succeeded then just
19884
             * create object from that because sums are
19885
             * not unique and can cause confusion. */
19886
            obj = wolfSSL_ASN1_OBJECT_new();
19887
            if (obj == NULL) {
19888
                WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct");
19889
                return NULL;
19890
            }
19891
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC;
19892
            obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL,
19893
                    DYNAMIC_TYPE_ASN1);
19894
            if (obj->obj == NULL) {
19895
                wolfSSL_ASN1_OBJECT_free(obj);
19896
                return NULL;
19897
            }
19898
            obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA;
19899
            i = SetObjectId((int)outSz, (byte*)obj->obj);
19900
            XMEMCPY((byte*)obj->obj + i, out, outSz);
19901
            obj->objSz = (word32)i + outSz;
19902
            return obj;
19903
        }
19904
19905
        /* TODO: update short names in wolfssl_object_info and check OID sums
19906
           are correct */
19907
        for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) {
19908
            /* Short name, long name, and numerical value are interpreted */
19909
            if (no_name == 0 &&
19910
                ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) ||
19911
                 (XSTRCMP(s, wolfssl_object_info[i].lName) == 0)))
19912
            {
19913
                    nid = wolfssl_object_info[i].nid;
19914
            }
19915
        }
19916
19917
        if (nid != WC_NID_undef)
19918
            return wolfSSL_OBJ_nid2obj(nid);
19919
19920
        return NULL;
19921
    }
19922
#endif
19923
19924
    /* compatibility function. Its intended use is to remove OID's from an
19925
     * internal table that have been added with OBJ_create. wolfSSL manages its
19926
     * own internal OID values and does not currently support OBJ_create. */
19927
    void wolfSSL_OBJ_cleanup(void)
19928
    {
19929
        WOLFSSL_ENTER("wolfSSL_OBJ_cleanup");
19930
    }
19931
19932
    #ifndef NO_WOLFSSL_STUB
19933
    int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln)
19934
    {
19935
        (void)oid;
19936
        (void)sn;
19937
        (void)ln;
19938
        WOLFSSL_STUB("wolfSSL_OBJ_create");
19939
        return WOLFSSL_FAILURE;
19940
    }
19941
    #endif
19942
19943
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
19944
    {
19945
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
19946
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
19947
        ssl->options.verifyDepth = (byte)depth;
19948
    #endif
19949
    }
19950
19951
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
19952
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
19953
19954
#ifdef OPENSSL_EXTRA
19955
19956
/* wolfSSL uses negative values for error states. This function returns an
19957
 * unsigned type so the value returned is the absolute value of the error.
19958
 */
19959
unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line)
19960
{
19961
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
19962
19963
    (void)line;
19964
    (void)file;
19965
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
19966
    {
19967
        int ret;
19968
19969
        if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) {
19970
            WOLFSSL_MSG("Issue peeking at error node in queue");
19971
            return 0;
19972
        }
19973
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \
19974
        || defined(WOLFSSL_HAPROXY)
19975
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
19976
            return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE;
19977
    #endif
19978
    #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
19979
        if (ret == ASN1_R_HEADER_TOO_LONG) {
19980
            return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG;
19981
        }
19982
    #endif
19983
        return (unsigned long)ret;
19984
    }
19985
#else
19986
    return (unsigned long)(0 - NOT_COMPILED_IN);
19987
#endif
19988
}
19989
19990
#endif /* OPENSSL_EXTRA */
19991
19992
#ifdef HAVE_EX_DATA_CRYPTO
19993
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
19994
19995
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
19996
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
19997
        WOLFSSL_CRYPTO_EX_free* free_func)
19998
{
19999
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
20000
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
20001
    if (new_ctx == NULL)
20002
        return WOLFSSL_FATAL_ERROR;
20003
    new_ctx->ctx_l = ctx_l;
20004
    new_ctx->ctx_ptr = ctx_ptr;
20005
    new_ctx->new_func = new_func;
20006
    new_ctx->free_func = free_func;
20007
    new_ctx->dup_func = dup_func;
20008
    new_ctx->next = NULL;
20009
    /* Push to end of list */
20010
    while (*dst != NULL)
20011
        dst = &(*dst)->next;
20012
    *dst = new_ctx;
20013
    return 0;
20014
}
20015
20016
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
20017
{
20018
    while (cb_ctx != NULL) {
20019
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
20020
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
20021
        cb_ctx = next;
20022
    }
20023
}
20024
20025
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
20026
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
20027
{
20028
    int idx = 0;
20029
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
20030
        if (cb_ctx->new_func != NULL)
20031
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
20032
                    cb_ctx->ctx_ptr);
20033
    }
20034
}
20035
20036
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
20037
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
20038
{
20039
    int idx = 0;
20040
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
20041
        if (cb_ctx->dup_func != NULL) {
20042
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
20043
            if (!cb_ctx->dup_func(out, in,
20044
                    &ptr, idx,
20045
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
20046
                return WOLFSSL_FAILURE;
20047
            }
20048
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
20049
        }
20050
    }
20051
    return WOLFSSL_SUCCESS;
20052
}
20053
20054
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
20055
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
20056
{
20057
    int idx = 0;
20058
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
20059
        if (cb_ctx->free_func != NULL)
20060
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
20061
                    cb_ctx->ctx_ptr);
20062
    }
20063
}
20064
20065
/**
20066
 * get_ex_new_index is a helper function for the following
20067
 * xx_get_ex_new_index functions:
20068
 *  - wolfSSL_CRYPTO_get_ex_new_index
20069
 *  - wolfSSL_CTX_get_ex_new_index
20070
 *  - wolfSSL_get_ex_new_index
20071
 * Issues a unique index number for the specified class-index.
20072
 * Returns an index number greater or equal to zero on success,
20073
 * -1 on failure.
20074
 */
20075
int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
20076
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
20077
        WOLFSSL_CRYPTO_EX_free* free_func)
20078
{
20079
    /* index counter for each class index*/
20080
    static int ctx_idx = 0;
20081
    static int ssl_idx = 0;
20082
    static int ssl_session_idx = 0;
20083
    static int x509_idx = 0;
20084
20085
    int idx = -1;
20086
20087
    switch(class_index) {
20088
        case WOLF_CRYPTO_EX_INDEX_SSL:
20089
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
20090
                    dup_func, free_func);
20091
            idx = ssl_idx++;
20092
            break;
20093
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
20094
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
20095
                    dup_func, free_func);
20096
            idx = ctx_idx++;
20097
            break;
20098
        case WOLF_CRYPTO_EX_INDEX_X509:
20099
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
20100
                    dup_func, free_func);
20101
            idx = x509_idx++;
20102
            break;
20103
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
20104
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
20105
                    new_func, dup_func, free_func) != 0)
20106
                return WOLFSSL_FATAL_ERROR;
20107
            idx = ssl_session_idx++;
20108
            break;
20109
20110
        /* following class indexes are not supoprted */
20111
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
20112
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
20113
        case WOLF_CRYPTO_EX_INDEX_DH:
20114
        case WOLF_CRYPTO_EX_INDEX_DSA:
20115
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
20116
        case WOLF_CRYPTO_EX_INDEX_RSA:
20117
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
20118
        case WOLF_CRYPTO_EX_INDEX_UI:
20119
        case WOLF_CRYPTO_EX_INDEX_BIO:
20120
        case WOLF_CRYPTO_EX_INDEX_APP:
20121
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
20122
        case WOLF_CRYPTO_EX_INDEX_DRBG:
20123
        default:
20124
            break;
20125
    }
20126
    if (idx >= MAX_EX_DATA)
20127
        return WOLFSSL_FATAL_ERROR;
20128
    return idx;
20129
}
20130
#endif /* HAVE_EX_DATA_CRYPTO */
20131
20132
#ifdef HAVE_EX_DATA_CRYPTO
20133
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
20134
                                 WOLFSSL_CRYPTO_EX_new* new_func,
20135
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
20136
                                 WOLFSSL_CRYPTO_EX_free* free_func)
20137
{
20138
20139
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
20140
20141
    return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx, arg,
20142
                                    new_func, dup_func, free_func);
20143
}
20144
20145
/* Return the index that can be used for the WOLFSSL structure to store
20146
 * application data.
20147
 *
20148
 */
20149
int wolfSSL_get_ex_new_index(long argValue, void* arg,
20150
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
20151
        WOLFSSL_CRYPTO_EX_free* cb3)
20152
{
20153
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
20154
20155
    return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue, arg,
20156
            cb1, cb2, cb3);
20157
}
20158
#endif /* HAVE_EX_DATA_CRYPTO */
20159
20160
#ifdef OPENSSL_EXTRA
20161
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
20162
{
20163
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
20164
#ifdef HAVE_EX_DATA
20165
    if (ctx != NULL) {
20166
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
20167
    }
20168
#else
20169
    (void)ctx;
20170
    (void)idx;
20171
#endif
20172
    return NULL;
20173
}
20174
20175
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
20176
{
20177
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
20178
#ifdef HAVE_EX_DATA
20179
    if (ctx != NULL) {
20180
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
20181
    }
20182
#else
20183
    (void)ctx;
20184
    (void)idx;
20185
    (void)data;
20186
#endif
20187
    return WOLFSSL_FAILURE;
20188
}
20189
20190
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
20191
int wolfSSL_CTX_set_ex_data_with_cleanup(
20192
    WOLFSSL_CTX* ctx,
20193
    int idx,
20194
    void* data,
20195
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
20196
{
20197
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
20198
    if (ctx != NULL) {
20199
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
20200
                                                       cleanup_routine);
20201
    }
20202
    return WOLFSSL_FAILURE;
20203
}
20204
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
20205
#endif /* OPENSSL_EXTRA */
20206
20207
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
20208
20209
/* Returns char* to app data stored in ex[0].
20210
 *
20211
 * ssl WOLFSSL structure to get app data from
20212
 */
20213
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
20214
{
20215
    /* checkout exdata stuff... */
20216
    WOLFSSL_ENTER("wolfSSL_get_app_data");
20217
20218
    return wolfSSL_get_ex_data(ssl, 0);
20219
}
20220
20221
20222
/* Set ex array 0 to have app data
20223
 *
20224
 * ssl WOLFSSL struct to set app data in
20225
 * arg data to be stored
20226
 *
20227
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
20228
 */
20229
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
20230
    WOLFSSL_ENTER("wolfSSL_set_app_data");
20231
20232
    return wolfSSL_set_ex_data(ssl, 0, arg);
20233
}
20234
20235
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
20236
20237
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
20238
0
{
20239
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
20240
#ifdef HAVE_EX_DATA
20241
    if (ssl != NULL) {
20242
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
20243
    }
20244
#else
20245
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
20246
0
    (void)ssl;
20247
0
    (void)idx;
20248
0
    (void)data;
20249
0
#endif
20250
0
    return WOLFSSL_FAILURE;
20251
0
}
20252
20253
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
20254
int wolfSSL_set_ex_data_with_cleanup(
20255
    WOLFSSL* ssl,
20256
    int idx,
20257
    void* data,
20258
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
20259
{
20260
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
20261
    if (ssl != NULL)
20262
    {
20263
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
20264
                                                       cleanup_routine);
20265
    }
20266
    return WOLFSSL_FAILURE;
20267
}
20268
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
20269
20270
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
20271
0
{
20272
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
20273
#ifdef HAVE_EX_DATA
20274
    if (ssl != NULL) {
20275
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
20276
    }
20277
#else
20278
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
20279
0
    (void)ssl;
20280
0
    (void)idx;
20281
0
#endif
20282
0
    return 0;
20283
0
}
20284
20285
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
20286
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
20287
20288
/* returns the enum value associated with handshake state
20289
 *
20290
 * ssl the WOLFSSL structure to get state of
20291
 */
20292
int wolfSSL_get_state(const WOLFSSL* ssl)
20293
{
20294
    WOLFSSL_ENTER("wolfSSL_get_state");
20295
20296
    if (ssl == NULL) {
20297
        WOLFSSL_MSG("Null argument passed in");
20298
        return WOLFSSL_FAILURE;
20299
    }
20300
20301
    return ssl->options.handShakeState;
20302
}
20303
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
20304
20305
#ifdef OPENSSL_EXTRA
20306
void wolfSSL_certs_clear(WOLFSSL* ssl)
20307
{
20308
    WOLFSSL_ENTER("wolfSSL_certs_clear");
20309
20310
    if (ssl == NULL)
20311
        return;
20312
20313
    /* ctx still owns certificate, certChain, key, dh, and cm */
20314
    if (ssl->buffers.weOwnCert) {
20315
        FreeDer(&ssl->buffers.certificate);
20316
        ssl->buffers.weOwnCert = 0;
20317
    }
20318
    ssl->buffers.certificate = NULL;
20319
    if (ssl->buffers.weOwnCertChain) {
20320
        FreeDer(&ssl->buffers.certChain);
20321
        ssl->buffers.weOwnCertChain = 0;
20322
    }
20323
    ssl->buffers.certChain = NULL;
20324
#ifdef WOLFSSL_TLS13
20325
    ssl->buffers.certChainCnt = 0;
20326
#endif
20327
    if (ssl->buffers.weOwnKey) {
20328
        FreeDer(&ssl->buffers.key);
20329
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
20330
        FreeDer(&ssl->buffers.keyMask);
20331
    #endif
20332
        ssl->buffers.weOwnKey = 0;
20333
    }
20334
    ssl->buffers.key      = NULL;
20335
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
20336
    ssl->buffers.keyMask  = NULL;
20337
#endif
20338
    ssl->buffers.keyType  = 0;
20339
    ssl->buffers.keyId    = 0;
20340
    ssl->buffers.keyLabel = 0;
20341
    ssl->buffers.keySz    = 0;
20342
    ssl->buffers.keyDevId = 0;
20343
#ifdef WOLFSSL_DUAL_ALG_CERTS
20344
    if (ssl->buffers.weOwnAltKey) {
20345
        FreeDer(&ssl->buffers.altKey);
20346
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
20347
        FreeDer(&ssl->buffers.altKeyMask);
20348
    #endif
20349
        ssl->buffers.weOwnAltKey = 0;
20350
    }
20351
    ssl->buffers.altKey     = NULL;
20352
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
20353
    ssl->buffers.altKeyMask = NULL;
20354
#endif
20355
#endif /* WOLFSSL_DUAL_ALG_CERTS */
20356
}
20357
#endif
20358
20359
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
20360
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
20361
20362
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
20363
{
20364
    WOLFSSL_ENTER("wolfSSL_ctrl");
20365
    if (ssl == NULL)
20366
        return BAD_FUNC_ARG;
20367
20368
    switch (cmd) {
20369
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
20370
            defined(OPENSSL_ALL)
20371
        #ifdef HAVE_SNI
20372
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
20373
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
20374
            if (pt == NULL) {
20375
                WOLFSSL_MSG("Passed in NULL Host Name.");
20376
                break;
20377
            }
20378
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
20379
        #endif /* HAVE_SNI */
20380
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
20381
        default:
20382
            WOLFSSL_MSG("Case not implemented.");
20383
    }
20384
    (void)opt;
20385
    (void)pt;
20386
    return WOLFSSL_FAILURE;
20387
}
20388
20389
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
20390
{
20391
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
20392
    long ctrl_opt;
20393
#endif
20394
    long ret = WOLFSSL_SUCCESS;
20395
20396
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
20397
    if (ctx == NULL)
20398
        return WOLFSSL_FAILURE;
20399
20400
    switch (cmd) {
20401
    case SSL_CTRL_CHAIN:
20402
#ifdef SESSION_CERTS
20403
    {
20404
        /*
20405
         * We don't care about opt here because a copy of the certificate is
20406
         * stored anyway so increasing the reference counter is not necessary.
20407
         * Just check to make sure that it is set to one of the correct values.
20408
         */
20409
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
20410
        WOLFSSL_X509* x509;
20411
        int i;
20412
        if (opt != 0 && opt != 1) {
20413
            ret = WOLFSSL_FAILURE;
20414
            break;
20415
        }
20416
        /* Clear certificate chain */
20417
        FreeDer(&ctx->certChain);
20418
        if (sk) {
20419
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
20420
                x509 = wolfSSL_sk_X509_value(sk, i);
20421
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
20422
                if (wolfSSL_X509_up_ref(x509) != 1) {
20423
                    WOLFSSL_MSG("Error increasing reference count");
20424
                    continue;
20425
                }
20426
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
20427
                        WOLFSSL_SUCCESS) {
20428
                    WOLFSSL_MSG("Error adding certificate to context");
20429
                    /* Decrease reference count on failure */
20430
                    wolfSSL_X509_free(x509);
20431
                    x509 = NULL;
20432
                }
20433
            }
20434
        }
20435
        /* Free previous chain */
20436
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
20437
        ctx->x509Chain = sk;
20438
        if (sk && opt == 1) {
20439
            /* up all refs when opt == 1 */
20440
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
20441
                x509 = wolfSSL_sk_X509_value(sk, i);
20442
                if (wolfSSL_X509_up_ref(x509) != 1) {
20443
                    WOLFSSL_MSG("Error increasing reference count");
20444
                    continue;
20445
                }
20446
            }
20447
        }
20448
    }
20449
#else
20450
        WOLFSSL_MSG("Session certificates not compiled in");
20451
        ret = WOLFSSL_FAILURE;
20452
#endif
20453
        break;
20454
20455
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
20456
    case SSL_CTRL_OPTIONS:
20457
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
20458
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
20459
20460
        #ifdef WOLFSSL_QT
20461
        /* Set whether to use client or server cipher preference */
20462
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
20463
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
20464
            WOLFSSL_MSG("Using Server's Cipher Preference.");
20465
            ctx->useClientOrder = 0;
20466
        } else {
20467
            WOLFSSL_MSG("Using Client's Cipher Preference.");
20468
            ctx->useClientOrder = 1;
20469
        }
20470
        #endif /* WOLFSSL_QT */
20471
20472
        return ctrl_opt;
20473
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
20474
    case SSL_CTRL_EXTRA_CHAIN_CERT:
20475
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
20476
        if (pt == NULL) {
20477
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
20478
            ret = WOLFSSL_FAILURE;
20479
            break;
20480
        }
20481
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
20482
20483
#ifndef NO_DH
20484
    case SSL_CTRL_SET_TMP_DH:
20485
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
20486
        if (pt == NULL) {
20487
            WOLFSSL_MSG("Passed in DH pointer NULL.");
20488
            ret = WOLFSSL_FAILURE;
20489
            break;
20490
        }
20491
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
20492
#endif
20493
20494
#ifdef HAVE_ECC
20495
    case SSL_CTRL_SET_TMP_ECDH:
20496
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
20497
        if (pt == NULL) {
20498
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
20499
            ret = WOLFSSL_FAILURE;
20500
            break;
20501
        }
20502
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
20503
#endif
20504
    case SSL_CTRL_MODE:
20505
        wolfSSL_CTX_set_mode(ctx,opt);
20506
        break;
20507
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
20508
        WOLFSSL_MSG("set min proto version");
20509
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
20510
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
20511
        WOLFSSL_MSG("set max proto version");
20512
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
20513
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
20514
        WOLFSSL_MSG("get min proto version");
20515
        return wolfSSL_CTX_get_min_proto_version(ctx);
20516
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
20517
        WOLFSSL_MSG("get max proto version");
20518
        return wolfSSL_CTX_get_max_proto_version(ctx);
20519
    default:
20520
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
20521
        ret = WOLFSSL_FAILURE;
20522
        break;
20523
    }
20524
20525
    (void)ctx;
20526
    (void)cmd;
20527
    (void)opt;
20528
    (void)pt;
20529
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
20530
    return ret;
20531
}
20532
20533
#ifndef NO_WOLFSSL_STUB
20534
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
20535
{
20536
    (void) ctx;
20537
    (void) cmd;
20538
    (void) fp;
20539
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
20540
    return WOLFSSL_FAILURE;
20541
20542
}
20543
#endif /* NO_WOLFSSL_STUB */
20544
20545
#ifndef NO_WOLFSSL_STUB
20546
long wolfSSL_CTX_clear_extra_chain_certs(WOLFSSL_CTX* ctx)
20547
{
20548
    return wolfSSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0L, NULL);
20549
}
20550
#endif
20551
20552
/* Returns the verifyCallback from the ssl structure if successful.
20553
Returns NULL otherwise. */
20554
VerifyCallback wolfSSL_get_verify_callback(WOLFSSL* ssl)
20555
{
20556
    WOLFSSL_ENTER("wolfSSL_get_verify_callback");
20557
    if (ssl) {
20558
        return ssl->verifyCallback;
20559
    }
20560
    return NULL;
20561
}
20562
20563
#ifndef NO_BIO
20564
/* Converts EVP_PKEY data from a bio buffer to a WOLFSSL_EVP_PKEY structure.
20565
Returns pointer to private EVP_PKEY struct upon success, NULL if there
20566
is a failure.*/
20567
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio,
20568
                                                         WOLFSSL_EVP_PKEY** out)
20569
{
20570
    unsigned char* mem = NULL;
20571
    int memSz = 0;
20572
    WOLFSSL_EVP_PKEY* key = NULL;
20573
    unsigned char* extraBioMem = NULL;
20574
20575
    WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_bio");
20576
20577
    if (bio == NULL) {
20578
        return NULL;
20579
    }
20580
    (void)out;
20581
20582
    memSz = wolfSSL_BIO_get_len(bio);
20583
    if (memSz <= 0) {
20584
        WOLFSSL_MSG("wolfSSL_BIO_get_len() failure");
20585
        return NULL;
20586
    }
20587
20588
    mem = (unsigned char*)XMALLOC((size_t)memSz, bio->heap,
20589
                                    DYNAMIC_TYPE_TMP_BUFFER);
20590
    if (mem == NULL) {
20591
        WOLFSSL_MSG("Malloc failure");
20592
        return NULL;
20593
    }
20594
20595
    if (wolfSSL_BIO_read(bio, (unsigned char*)mem, memSz) == memSz) {
20596
        int extraBioMemSz;
20597
        int derLength;
20598
20599
        /* Determines key type and returns the new private EVP_PKEY object */
20600
        if ((key = wolfSSL_d2i_PrivateKey_EVP(NULL, &mem, (long)memSz)) ==
20601
                NULL) {
20602
            WOLFSSL_MSG("wolfSSL_d2i_PrivateKey_EVP() failure");
20603
            XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
20604
            return NULL;
20605
        }
20606
20607
        /* Write extra data back into bio object if necessary. */
20608
        derLength = key->pkey_sz;
20609
        extraBioMemSz = (memSz - derLength);
20610
        if (extraBioMemSz > 0) {
20611
            int i;
20612
            int j = 0;
20613
20614
            extraBioMem = (unsigned char *)XMALLOC((size_t)extraBioMemSz, NULL,
20615
                                                       DYNAMIC_TYPE_TMP_BUFFER);
20616
            if (extraBioMem == NULL) {
20617
                WOLFSSL_MSG("Malloc failure");
20618
                XFREE((unsigned char*)extraBioMem, bio->heap,
20619
                                                       DYNAMIC_TYPE_TMP_BUFFER);
20620
                XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
20621
                return NULL;
20622
            }
20623
20624
            for (i = derLength; i < memSz; i++) {
20625
                *(extraBioMem + j) = *(mem + i);
20626
                j++;
20627
            }
20628
20629
            wolfSSL_BIO_write(bio, extraBioMem, extraBioMemSz);
20630
            if (wolfSSL_BIO_get_len(bio) <= 0) {
20631
                WOLFSSL_MSG("Failed to write memory to bio");
20632
                XFREE((unsigned char*)extraBioMem, bio->heap,
20633
                                                       DYNAMIC_TYPE_TMP_BUFFER);
20634
                XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
20635
                return NULL;
20636
            }
20637
            XFREE((unsigned char*)extraBioMem, bio->heap,
20638
                                                       DYNAMIC_TYPE_TMP_BUFFER);
20639
        }
20640
20641
        if (out != NULL) {
20642
            *out = key;
20643
        }
20644
    }
20645
    XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
20646
    return key;
20647
}
20648
#endif /* !NO_BIO */
20649
20650
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
20651
20652
20653
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
20654
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) || \
20655
    defined(WOLFSSL_QT) || defined(WOLFSSL_WPAS_SMALL)
20656
20657
/* Converts a DER encoded private key to a WOLFSSL_EVP_PKEY structure.
20658
 * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL
20659
 * on fail */
20660
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_EVP(WOLFSSL_EVP_PKEY** out,
20661
                                                  unsigned char** in, long inSz)
20662
{
20663
    WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_EVP");
20664
    return d2iGenericKey(out, (const unsigned char**)in, inSz, 1);
20665
}
20666
20667
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT ||
20668
        * WOLFSSL_WPAS_SMALL*/
20669
20670
20671
/* stunnel compatibility functions*/
20672
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
20673
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
20674
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
20675
     defined(WOLFSSL_OPENSSH)))
20676
void wolfSSL_ERR_remove_thread_state(void* pid)
20677
{
20678
    (void) pid;
20679
    return;
20680
}
20681
20682
#ifndef NO_FILESYSTEM
20683
/***TBD ***/
20684
void wolfSSL_print_all_errors_fp(XFILE fp)
20685
{
20686
    (void)fp;
20687
}
20688
#endif /* !NO_FILESYSTEM */
20689
20690
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
20691
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
20692
20693
/* Note: This is a huge section of API's - through
20694
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
20695
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
20696
20697
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
20698
    !defined(WOLFSSL_STATIC_MEMORY)
20699
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
20700
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
20701
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
20702
20703
static void* OSSL_Malloc(size_t size)
20704
{
20705
    if (ossl_malloc != NULL)
20706
        return ossl_malloc(size, NULL, 0);
20707
    else
20708
        return NULL;
20709
}
20710
20711
static void  OSSL_Free(void *ptr)
20712
{
20713
    if (ossl_free != NULL)
20714
        ossl_free(ptr, NULL, 0);
20715
}
20716
20717
static void* OSSL_Realloc(void *ptr, size_t size)
20718
{
20719
    if (ossl_realloc != NULL)
20720
        return ossl_realloc(ptr, size, NULL, 0);
20721
    else
20722
        return NULL;
20723
}
20724
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
20725
        * !WOLFSSL_STATIC_MEMORY */
20726
20727
int wolfSSL_CRYPTO_set_mem_functions(
20728
        wolfSSL_OSSL_Malloc_cb  m,
20729
        wolfSSL_OSSL_Realloc_cb r,
20730
        wolfSSL_OSSL_Free_cb    f)
20731
{
20732
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
20733
#ifdef WOLFSSL_DEBUG_MEMORY
20734
    WOLFSSL_MSG("mem functions will receive function name instead of "
20735
                "file name");
20736
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
20737
            (wolfSSL_Realloc_cb)r) == 0)
20738
        return WOLFSSL_SUCCESS;
20739
#else
20740
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
20741
                "functions will receive a NULL file name and 0 for the "
20742
                "line number.");
20743
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
20744
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
20745
        ossl_malloc = m;
20746
        ossl_free = f;
20747
        ossl_realloc = r;
20748
        return WOLFSSL_SUCCESS;
20749
    }
20750
#endif
20751
    else
20752
        return WOLFSSL_FAILURE;
20753
#else
20754
    (void)m;
20755
    (void)r;
20756
    (void)f;
20757
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
20758
    return WOLFSSL_FAILURE;
20759
#endif
20760
}
20761
20762
int wolfSSL_ERR_load_ERR_strings(void)
20763
{
20764
    return WOLFSSL_SUCCESS;
20765
}
20766
20767
void wolfSSL_ERR_load_crypto_strings(void)
20768
{
20769
    WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings");
20770
    /* Do nothing */
20771
    return;
20772
}
20773
20774
int wolfSSL_FIPS_mode(void)
20775
{
20776
#ifdef HAVE_FIPS
20777
    return 1;
20778
#else
20779
    return 0;
20780
#endif
20781
}
20782
20783
int wolfSSL_FIPS_mode_set(int r)
20784
{
20785
#ifdef HAVE_FIPS
20786
    if (r == 0) {
20787
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
20788
        return WOLFSSL_FAILURE;
20789
    }
20790
    return WOLFSSL_SUCCESS;
20791
#else
20792
    if (r == 0) {
20793
        return WOLFSSL_SUCCESS;
20794
    }
20795
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
20796
    return WOLFSSL_FAILURE;
20797
#endif
20798
}
20799
20800
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
20801
{
20802
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
20803
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
20804
20805
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
20806
    (void)alg_bits;
20807
    if (c!= NULL)
20808
        ret = c->bits;
20809
    #else
20810
    if (c != NULL && c->ssl != NULL) {
20811
        ret = 8 * c->ssl->specs.key_size;
20812
        if (alg_bits != NULL) {
20813
            *alg_bits = ret;
20814
        }
20815
    }
20816
    #endif
20817
    return ret;
20818
}
20819
20820
#ifdef HAVE_SNI
20821
int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name)
20822
{
20823
    int ret;
20824
    WOLFSSL_ENTER("wolfSSL_set_tlsext_host_name");
20825
    ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME,
20826
            host_name, (word16)XSTRLEN(host_name));
20827
    WOLFSSL_LEAVE("wolfSSL_set_tlsext_host_name", ret);
20828
    return ret;
20829
}
20830
20831
#ifndef NO_WOLFSSL_SERVER
20832
/* May be called by server to get the requested accepted name and by the client
20833
 * to get the requested name. */
20834
const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type)
20835
{
20836
    void * serverName = NULL;
20837
    if (ssl == NULL)
20838
        return NULL;
20839
    TLSX_SNI_GetRequest(ssl->extensions, type, &serverName,
20840
            !wolfSSL_is_server(ssl));
20841
    return (const char *)serverName;
20842
}
20843
#endif
20844
20845
#endif /* HAVE_SNI */
20846
20847
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
20848
{
20849
    int ret;
20850
    /* This method requires some explanation. Its sibling is
20851
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
20852
     * which re-inits the WOLFSSL* with all settings in the new CTX.
20853
     * That one is the right one to use *before* a handshake is started.
20854
     *
20855
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
20856
     * when a server inspects the SNI in a ClientHello callback and
20857
     * decides which set of certificates to use.
20858
     *
20859
     * Since, at the time the SNI callback is run, some decisions on
20860
     * Extensions or the ServerHello might already have been taken, this
20861
     * method is very restricted in what it does:
20862
     * - changing the server certificate(s)
20863
     * - changing the server id for session handling
20864
     * and everything else in WOLFSSL* needs to remain untouched.
20865
     */
20866
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
20867
    if (ssl == NULL || ctx == NULL)
20868
        return NULL;
20869
    if (ssl->ctx == ctx)
20870
        return ssl->ctx;
20871
20872
    if (ctx->suites == NULL) {
20873
        /* suites */
20874
        if (AllocateCtxSuites(ctx) != 0)
20875
            return NULL;
20876
        InitSSL_CTX_Suites(ctx);
20877
    }
20878
20879
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
20880
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
20881
    if (ret != 0) {
20882
        /* can only fail on serious stuff, like mutex not working
20883
         * or ctx refcount out of whack. */
20884
        return NULL;
20885
    }
20886
#else
20887
    (void)ret;
20888
#endif
20889
    if (ssl->ctx != NULL)
20890
        wolfSSL_CTX_free(ssl->ctx);
20891
    ssl->ctx = ctx;
20892
20893
#ifndef NO_CERTS
20894
#ifdef WOLFSSL_COPY_CERT
20895
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
20896
    if (ctx->certificate != NULL) {
20897
        if (ssl->buffers.certificate != NULL) {
20898
            FreeDer(&ssl->buffers.certificate);
20899
            ssl->buffers.certificate = NULL;
20900
        }
20901
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
20902
            ctx->certificate->length, ctx->certificate->type,
20903
            ctx->certificate->heap);
20904
        if (ret != 0) {
20905
            ssl->buffers.weOwnCert = 0;
20906
            return NULL;
20907
        }
20908
20909
        ssl->buffers.weOwnCert = 1;
20910
    }
20911
    if (ctx->certChain != NULL) {
20912
        if (ssl->buffers.certChain != NULL) {
20913
            FreeDer(&ssl->buffers.certChain);
20914
            ssl->buffers.certChain = NULL;
20915
        }
20916
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
20917
            ctx->certChain->length, ctx->certChain->type,
20918
            ctx->certChain->heap);
20919
        if (ret != 0) {
20920
            ssl->buffers.weOwnCertChain = 0;
20921
            return NULL;
20922
        }
20923
20924
        ssl->buffers.weOwnCertChain = 1;
20925
    }
20926
#else
20927
    /* ctx owns certificate, certChain and key */
20928
    ssl->buffers.certificate = ctx->certificate;
20929
    ssl->buffers.certChain = ctx->certChain;
20930
#endif
20931
#ifdef WOLFSSL_TLS13
20932
    ssl->buffers.certChainCnt = ctx->certChainCnt;
20933
#endif
20934
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
20935
#ifdef WOLFSSL_COPY_KEY
20936
    if (ctx->privateKey != NULL) {
20937
        if (ssl->buffers.key != NULL) {
20938
            FreeDer(&ssl->buffers.key);
20939
            ssl->buffers.key = NULL;
20940
        }
20941
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
20942
            ctx->privateKey->length, ctx->privateKey->type,
20943
            ctx->privateKey->heap);
20944
        if (ret != 0) {
20945
            ssl->buffers.weOwnKey = 0;
20946
            return NULL;
20947
        }
20948
        ssl->buffers.weOwnKey = 1;
20949
    }
20950
    else {
20951
        ssl->buffers.key      = ctx->privateKey;
20952
    }
20953
#else
20954
    ssl->buffers.key      = ctx->privateKey;
20955
#endif
20956
#else
20957
    if (ctx->privateKey != NULL) {
20958
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
20959
            ctx->privateKey->length, ctx->privateKey->type,
20960
            ctx->privateKey->heap);
20961
        if (ret != 0) {
20962
            return NULL;
20963
        }
20964
        /* Blind the private key for the SSL with new random mask. */
20965
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
20966
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
20967
            &ssl->buffers.keyMask);
20968
        if (ret != 0) {
20969
            return NULL;
20970
        }
20971
    }
20972
#endif
20973
    ssl->buffers.keyType  = ctx->privateKeyType;
20974
    ssl->buffers.keyId    = ctx->privateKeyId;
20975
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
20976
    ssl->buffers.keySz    = ctx->privateKeySz;
20977
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
20978
    /* flags indicating what certs/keys are available */
20979
    ssl->options.haveRSA          = ctx->haveRSA;
20980
    ssl->options.haveDH           = ctx->haveDH;
20981
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
20982
    ssl->options.haveECC          = ctx->haveECC;
20983
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
20984
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
20985
    ssl->options.haveDilithiumSig = ctx->haveDilithiumSig;
20986
#ifdef WOLFSSL_DUAL_ALG_CERTS
20987
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
20988
    ssl->buffers.altKey   = ctx->altPrivateKey;
20989
#else
20990
    if (ctx->altPrivateKey != NULL) {
20991
        ret = AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer,
20992
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
20993
            ctx->altPrivateKey->heap);
20994
        if (ret != 0) {
20995
            return NULL;
20996
        }
20997
        /* Blind the private key for the SSL with new random mask. */
20998
        wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask);
20999
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
21000
            &ssl->buffers.altKeyMask);
21001
        if (ret != 0) {
21002
            return NULL;
21003
        }
21004
    }
21005
#endif
21006
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
21007
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
21008
#endif /* WOLFSSL_DUAL_ALG_CERTS */
21009
#endif
21010
21011
#ifdef WOLFSSL_SESSION_ID_CTX
21012
    /* copy over application session context ID */
21013
    ssl->sessionCtxSz = ctx->sessionCtxSz;
21014
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
21015
#endif
21016
21017
    return ssl->ctx;
21018
}
21019
21020
21021
VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx)
21022
{
21023
    WOLFSSL_ENTER("wolfSSL_CTX_get_verify_callback");
21024
    if(ctx)
21025
        return ctx->verifyCallback;
21026
    return NULL;
21027
}
21028
21029
#ifdef HAVE_SNI
21030
/* this is a compatibility function, consider using
21031
 * wolfSSL_CTX_set_servername_callback */
21032
int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx,
21033
                                               CallbackSniRecv cb)
21034
{
21035
    WOLFSSL_ENTER("wolfSSL_CTX_set_tlsext_servername_callback");
21036
    if (ctx) {
21037
        ctx->sniRecvCb = cb;
21038
        return WOLFSSL_SUCCESS;
21039
    }
21040
    return WOLFSSL_FAILURE;
21041
}
21042
21043
#endif /* HAVE_SNI */
21044
21045
#ifndef NO_BIO
21046
void wolfSSL_ERR_load_BIO_strings(void) {
21047
    WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings");
21048
    /* do nothing */
21049
}
21050
#endif
21051
21052
#ifndef NO_WOLFSSL_STUB
21053
/* Set THREADID callback, return 1 on success, 0 on error */
21054
int wolfSSL_THREADID_set_callback(
21055
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
21056
{
21057
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
21058
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
21059
    (void)threadid_func;
21060
    return 1;
21061
}
21062
#endif
21063
21064
#ifndef NO_WOLFSSL_STUB
21065
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
21066
{
21067
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
21068
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
21069
    (void)id;
21070
    (void)val;
21071
    return;
21072
}
21073
#endif
21074
21075
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
21076
21077
#ifdef HAVE_SNI
21078
21079
void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb)
21080
0
{
21081
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_servername_callback");
21082
0
    if (ctx)
21083
0
        ctx->sniRecvCb = cb;
21084
0
}
21085
21086
21087
int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg)
21088
0
{
21089
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_servername_arg");
21090
0
    if (ctx) {
21091
0
        ctx->sniRecvCbArg = arg;
21092
0
        return WOLFSSL_SUCCESS;
21093
0
    }
21094
0
    return WOLFSSL_FAILURE;
21095
0
}
21096
21097
#endif /* HAVE_SNI */
21098
21099
#if defined(OPENSSL_EXTRA)
21100
21101
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
21102
{
21103
    if (!a || !b)
21104
        return 0;
21105
    return ConstantCompare((const byte*)a, (const byte*)b, (int)size);
21106
}
21107
21108
unsigned long wolfSSL_ERR_peek_last_error(void)
21109
{
21110
    WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error");
21111
21112
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
21113
    {
21114
        int ret;
21115
21116
        if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) {
21117
            WOLFSSL_MSG("Issue peeking at error node in queue");
21118
            return 0;
21119
        }
21120
        if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
21121
            return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
21122
    #if defined(WOLFSSL_PYTHON)
21123
        if (ret == ASN1_R_HEADER_TOO_LONG)
21124
            return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
21125
    #endif
21126
        return (unsigned long)ret;
21127
    }
21128
#else
21129
    return (unsigned long)(0 - NOT_COMPILED_IN);
21130
#endif
21131
}
21132
21133
#endif /* OPENSSL_EXTRA */
21134
21135
int wolfSSL_version(WOLFSSL* ssl)
21136
0
{
21137
0
    WOLFSSL_ENTER("wolfSSL_version");
21138
0
    if (ssl->version.major == SSLv3_MAJOR) {
21139
0
        switch (ssl->version.minor) {
21140
0
            case SSLv3_MINOR :
21141
0
                return SSL3_VERSION;
21142
0
            case TLSv1_MINOR :
21143
0
                return TLS1_VERSION;
21144
0
            case TLSv1_1_MINOR :
21145
0
                return TLS1_1_VERSION;
21146
0
            case TLSv1_2_MINOR :
21147
0
                return TLS1_2_VERSION;
21148
0
            case TLSv1_3_MINOR :
21149
0
                return TLS1_3_VERSION;
21150
0
            default:
21151
0
                return WOLFSSL_FAILURE;
21152
0
        }
21153
0
    }
21154
0
    else if (ssl->version.major == DTLS_MAJOR) {
21155
0
        switch (ssl->version.minor) {
21156
0
            case DTLS_MINOR :
21157
0
                return DTLS1_VERSION;
21158
0
            case DTLSv1_2_MINOR :
21159
0
                return DTLS1_2_VERSION;
21160
0
            case DTLSv1_3_MINOR:
21161
0
                return DTLS1_3_VERSION;
21162
0
            default:
21163
0
                return WOLFSSL_FAILURE;
21164
0
        }
21165
0
    }
21166
0
    return WOLFSSL_FAILURE;
21167
0
}
21168
21169
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
21170
0
{
21171
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
21172
0
    return ssl->ctx;
21173
0
}
21174
21175
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \
21176
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX)
21177
21178
/* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */
21179
int wolfSSL_get_verify_mode(const WOLFSSL* ssl)
21180
{
21181
    int mode = 0;
21182
    WOLFSSL_ENTER("wolfSSL_get_verify_mode");
21183
21184
    if (!ssl) {
21185
        return WOLFSSL_FAILURE;
21186
    }
21187
21188
    if (ssl->options.verifyNone) {
21189
        mode = WOLFSSL_VERIFY_NONE;
21190
    }
21191
    else {
21192
        if (ssl->options.verifyPeer) {
21193
            mode |= WOLFSSL_VERIFY_PEER;
21194
        }
21195
        if (ssl->options.failNoCert) {
21196
            mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
21197
        }
21198
        if (ssl->options.failNoCertxPSK) {
21199
            mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
21200
        }
21201
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
21202
        if (ssl->options.verifyPostHandshake) {
21203
            mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
21204
        }
21205
#endif
21206
    }
21207
21208
    WOLFSSL_LEAVE("wolfSSL_get_verify_mode", mode);
21209
    return mode;
21210
}
21211
21212
int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx)
21213
{
21214
    int mode = 0;
21215
    WOLFSSL_ENTER("wolfSSL_CTX_get_verify_mode");
21216
21217
    if (!ctx) {
21218
        return WOLFSSL_FAILURE;
21219
    }
21220
21221
    if (ctx->verifyNone) {
21222
        mode = WOLFSSL_VERIFY_NONE;
21223
    }
21224
    else {
21225
        if (ctx->verifyPeer) {
21226
            mode |= WOLFSSL_VERIFY_PEER;
21227
        }
21228
        if (ctx->failNoCert) {
21229
            mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT;
21230
        }
21231
        if (ctx->failNoCertxPSK) {
21232
            mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK;
21233
        }
21234
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
21235
        if (ctx->verifyPostHandshake) {
21236
            mode |= WOLFSSL_VERIFY_POST_HANDSHAKE;
21237
        }
21238
#endif
21239
    }
21240
21241
    WOLFSSL_LEAVE("wolfSSL_CTX_get_verify_mode", mode);
21242
    return mode;
21243
}
21244
21245
#endif
21246
21247
#ifdef WOLFSSL_JNI
21248
21249
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
21250
{
21251
    WOLFSSL_ENTER("wolfSSL_set_jobject");
21252
    if (ssl != NULL)
21253
    {
21254
        ssl->jObjectRef = objPtr;
21255
        return WOLFSSL_SUCCESS;
21256
    }
21257
    return WOLFSSL_FAILURE;
21258
}
21259
21260
void* wolfSSL_get_jobject(WOLFSSL* ssl)
21261
{
21262
    WOLFSSL_ENTER("wolfSSL_get_jobject");
21263
    if (ssl != NULL)
21264
        return ssl->jObjectRef;
21265
    return NULL;
21266
}
21267
21268
#endif /* WOLFSSL_JNI */
21269
21270
21271
#ifdef WOLFSSL_ASYNC_CRYPT
21272
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
21273
    WOLF_EVENT_FLAG flags, int* eventCount)
21274
{
21275
    if (ctx == NULL) {
21276
        return BAD_FUNC_ARG;
21277
    }
21278
21279
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
21280
                                        events, maxEvents, flags, eventCount);
21281
}
21282
21283
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
21284
{
21285
    int ret, eventCount = 0;
21286
    WOLF_EVENT* events[1];
21287
21288
    if (ssl == NULL) {
21289
        return BAD_FUNC_ARG;
21290
    }
21291
21292
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
21293
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
21294
    if (ret == 0) {
21295
        ret = eventCount;
21296
    }
21297
21298
    return ret;
21299
}
21300
#endif /* WOLFSSL_ASYNC_CRYPT */
21301
21302
#ifdef OPENSSL_EXTRA
21303
21304
static int peek_ignore_err(int err)
21305
{
21306
  switch(err) {
21307
    case -WC_NO_ERR_TRACE(WANT_READ):
21308
    case -WC_NO_ERR_TRACE(WANT_WRITE):
21309
    case -WC_NO_ERR_TRACE(ZERO_RETURN):
21310
    case -WOLFSSL_ERROR_ZERO_RETURN:
21311
    case -WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E):
21312
    case -WC_NO_ERR_TRACE(SOCKET_ERROR_E):
21313
      return 1;
21314
    default:
21315
      return 0;
21316
  }
21317
}
21318
21319
unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line,
21320
                                               const char **data, int *flags)
21321
{
21322
  unsigned long err;
21323
21324
    WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data");
21325
    err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err);
21326
21327
    if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER))
21328
        return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E);
21329
#ifdef OPENSSL_ALL
21330
    /* PARSE_ERROR is returned if an HTTP request is detected. */
21331
    else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR))
21332
        return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */;
21333
#endif
21334
#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON)
21335
    else if (err == ASN1_R_HEADER_TOO_LONG)
21336
        return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E);
21337
#endif
21338
  return err;
21339
}
21340
#endif
21341
21342
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
21343
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
21344
21345
#if !defined(WOLFSSL_USER_IO)
21346
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
21347
 * example input would be "127.0.0.1" and the returned value would be 7F000001
21348
 */
21349
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
21350
{
21351
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
21352
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
21353
    int  af = WOLFSSL_IP4;
21354
    WOLFSSL_ASN1_STRING *ret = NULL;
21355
21356
    if (ipa == NULL)
21357
        return NULL;
21358
21359
    if (XSTRSTR(ipa, ":") != NULL) {
21360
        af = WOLFSSL_IP6;
21361
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
21362
    }
21363
21364
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
21365
#ifdef FREESCALE_MQX
21366
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
21367
#else
21368
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
21369
#endif
21370
        WOLFSSL_MSG("Error parsing IP address");
21371
        return NULL;
21372
    }
21373
21374
    ret = wolfSSL_ASN1_STRING_new();
21375
    if (ret != NULL) {
21376
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
21377
            WOLFSSL_MSG("Error setting the string");
21378
            wolfSSL_ASN1_STRING_free(ret);
21379
            ret = NULL;
21380
        }
21381
    }
21382
21383
    return ret;
21384
}
21385
#endif /* !WOLFSSL_USER_IO */
21386
21387
/* Is the specified cipher suite a fake one used an an extension proxy? */
21388
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
21389
{
21390
    (void)suite0;
21391
    (void)suite;
21392
#ifdef HAVE_RENEGOTIATION_INDICATION
21393
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
21394
        return 1;
21395
#endif
21396
    return 0;
21397
}
21398
21399
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
21400
        byte suite)
21401
{
21402
    const CipherSuiteInfo* cipher_names = GetCipherNames();
21403
    int cipherSz = GetCipherNamesSize();
21404
    int i;
21405
    for (i = 0; i < cipherSz; i++)
21406
        if (cipher_names[i].cipherSuite0 == suite0 &&
21407
                cipher_names[i].cipherSuite == suite)
21408
            break;
21409
    if (i == cipherSz)
21410
        return 1;
21411
    /* Check min version */
21412
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
21413
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
21414
                cipher_names[i].minor >= TLSv1_MINOR)
21415
            /* 1.0 ciphersuites are in general available in 1.1 and
21416
             * 1.1 ciphersuites are in general available in 1.2 */
21417
            return 0;
21418
        return 1;
21419
    }
21420
    /* Check max version */
21421
    switch (cipher_names[i].minor) {
21422
    case SSLv3_MINOR :
21423
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
21424
    case TLSv1_MINOR :
21425
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
21426
    case TLSv1_1_MINOR :
21427
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
21428
    case TLSv1_2_MINOR :
21429
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
21430
    case TLSv1_3_MINOR :
21431
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
21432
    default:
21433
        WOLFSSL_MSG("Unrecognized minor version");
21434
        return 1;
21435
    }
21436
}
21437
21438
/* returns a pointer to internal cipher suite list. Should not be free'd by
21439
 * caller.
21440
 */
21441
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
21442
{
21443
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
21444
    const Suites* suites;
21445
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
21446
    const CipherSuiteInfo* cipher_names = GetCipherNames();
21447
    int cipherSz = GetCipherNamesSize();
21448
#endif
21449
21450
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
21451
    if (ssl == NULL)
21452
        return NULL;
21453
21454
    suites = WOLFSSL_SUITES(ssl);
21455
    if (suites == NULL)
21456
        return NULL;
21457
21458
    /* check if stack needs populated */
21459
    if (ssl->suitesStack == NULL) {
21460
        int i;
21461
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
21462
        int j;
21463
21464
        /* higher priority of cipher suite will be on top of stack */
21465
        for (i = suites->suiteSz - 2; i >=0; i-=2) {
21466
#else
21467
        for (i = 0; i < suites->suiteSz; i+=2) {
21468
#endif
21469
            WOLFSSL_STACK* add;
21470
21471
            /* A couple of suites are placeholders for special options,
21472
             * skip those. */
21473
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
21474
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
21475
                                            suites->suites[i+1])) {
21476
                continue;
21477
            }
21478
21479
            add = wolfSSL_sk_new_node(ssl->heap);
21480
            if (add != NULL) {
21481
                add->type = STACK_TYPE_CIPHER;
21482
                add->data.cipher.cipherSuite0 = suites->suites[i];
21483
                add->data.cipher.cipherSuite  = suites->suites[i+1];
21484
                add->data.cipher.ssl          = ssl;
21485
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
21486
                for (j = 0; j < cipherSz; j++) {
21487
                    if (cipher_names[j].cipherSuite0 ==
21488
                            add->data.cipher.cipherSuite0 &&
21489
                            cipher_names[j].cipherSuite ==
21490
                                    add->data.cipher.cipherSuite) {
21491
                        add->data.cipher.offset = (unsigned long)j;
21492
                        break;
21493
                    }
21494
                }
21495
#endif
21496
                #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
21497
                /* in_stack is checked in wolfSSL_CIPHER_description */
21498
                add->data.cipher.in_stack     = 1;
21499
                #endif
21500
21501
                add->next = ret;
21502
                if (ret != NULL) {
21503
                    add->num = ret->num + 1;
21504
                }
21505
                else {
21506
                    add->num = 1;
21507
                }
21508
                ret = add;
21509
            }
21510
        }
21511
        ((WOLFSSL*)ssl)->suitesStack = ret;
21512
    }
21513
    return ssl->suitesStack;
21514
}
21515
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
21516
#ifdef OPENSSL_ALL
21517
/* returned pointer is to an internal element in WOLFSSL struct and should not
21518
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
21519
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
21520
{
21521
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
21522
    const CipherSuiteInfo* cipher_names = GetCipherNames();
21523
    int cipherSz = GetCipherNamesSize();
21524
    const Suites* suites;
21525
21526
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
21527
21528
    if (ssl == NULL) {
21529
        return NULL;
21530
    }
21531
21532
    /* return NULL if is client side */
21533
    if (wolfSSL_is_server(ssl) == 0) {
21534
        return NULL;
21535
    }
21536
21537
    suites = ssl->clSuites;
21538
    if (suites == NULL) {
21539
        WOLFSSL_MSG("No client suites stored");
21540
    }
21541
    else if (ssl->clSuitesStack != NULL) {
21542
        ret = ssl->clSuitesStack;
21543
    }
21544
    else { /* generate cipher suites stack if not already done */
21545
        int i;
21546
        int j;
21547
21548
        ret = wolfSSL_sk_new_node(ssl->heap);
21549
        if (ret != NULL) {
21550
            ret->type = STACK_TYPE_CIPHER;
21551
21552
            /* higher priority of cipher suite will be on top of stack */
21553
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
21554
                WOLFSSL_CIPHER cipher;
21555
21556
                /* A couple of suites are placeholders for special options,
21557
                 * skip those. */
21558
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
21559
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
21560
                                                suites->suites[i+1])) {
21561
                    continue;
21562
                }
21563
21564
                cipher.cipherSuite0 = suites->suites[i];
21565
                cipher.cipherSuite  = suites->suites[i+1];
21566
                cipher.ssl          = ssl;
21567
                for (j = 0; j < cipherSz; j++) {
21568
                    if (cipher_names[j].cipherSuite0 ==
21569
                            cipher.cipherSuite0 &&
21570
                            cipher_names[j].cipherSuite ==
21571
                                    cipher.cipherSuite) {
21572
                        cipher.offset = (unsigned long)j;
21573
                        break;
21574
                    }
21575
                }
21576
21577
                /* in_stack is checked in wolfSSL_CIPHER_description */
21578
                cipher.in_stack     = 1;
21579
21580
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
21581
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
21582
                    wolfSSL_sk_CIPHER_free(ret);
21583
                    ret = NULL;
21584
                    break;
21585
                }
21586
            }
21587
        }
21588
        ssl->clSuitesStack = ret;
21589
    }
21590
    return ret;
21591
}
21592
#endif /* OPENSSL_ALL */
21593
21594
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
21595
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
21596
{
21597
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
21598
21599
    if (ctx == NULL)
21600
        return 0;
21601
21602
    return ctx->timeout;
21603
}
21604
21605
21606
/* returns the time in seconds of the current timeout */
21607
long wolfSSL_get_timeout(WOLFSSL* ssl)
21608
{
21609
    WOLFSSL_ENTER("wolfSSL_get_timeout");
21610
21611
    if (ssl == NULL)
21612
        return 0;
21613
    return ssl->timeout;
21614
}
21615
#endif
21616
21617
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
21618
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
21619
21620
#ifdef HAVE_ECC
21621
int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh)
21622
{
21623
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_set_tmp_ecdh");
21624
21625
    if (ctx == NULL || ecdh == NULL)
21626
        return BAD_FUNC_ARG;
21627
21628
    ctx->ecdhCurveOID = (word32)ecdh->group->curve_oid;
21629
21630
    return WOLFSSL_SUCCESS;
21631
}
21632
#endif
21633
#ifndef NO_BIO
21634
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
21635
{
21636
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
21637
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
21638
     * The setting buffer size doesn't do anything so return NULL for both.
21639
     */
21640
    if (s == NULL)
21641
        return NULL;
21642
21643
    return s->biord;
21644
}
21645
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
21646
{
21647
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
21648
    (void)s;
21649
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
21650
     * The setting buffer size doesn't do anything so return NULL for both.
21651
     */
21652
    if (s == NULL)
21653
        return NULL;
21654
21655
    return s->biowr;
21656
}
21657
#endif /* !NO_BIO */
21658
21659
#ifndef NO_TLS
21660
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
21661
{
21662
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
21663
    if (s == NULL)
21664
        return WOLFSSL_FAILURE;
21665
21666
    if (s->options.side == WOLFSSL_CLIENT_END) {
21667
    #ifndef NO_WOLFSSL_CLIENT
21668
        return wolfSSL_connect(s);
21669
    #else
21670
        WOLFSSL_MSG("Client not compiled in");
21671
        return WOLFSSL_FAILURE;
21672
    #endif
21673
    }
21674
21675
#ifndef NO_WOLFSSL_SERVER
21676
    return wolfSSL_accept(s);
21677
#else
21678
    WOLFSSL_MSG("Server not compiled in");
21679
    return WOLFSSL_FAILURE;
21680
#endif
21681
}
21682
21683
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
21684
{
21685
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
21686
#ifdef WOLFSSL_QUIC
21687
    if (WOLFSSL_IS_QUIC(s)) {
21688
        return wolfSSL_quic_do_handshake(s);
21689
    }
21690
#endif
21691
    return wolfSSL_SSL_do_handshake_internal(s);
21692
}
21693
#endif /* !NO_TLS */
21694
21695
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
21696
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
21697
#else
21698
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
21699
#endif
21700
{
21701
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
21702
21703
    return !wolfSSL_is_init_finished(ssl);
21704
}
21705
21706
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
21707
{
21708
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
21709
21710
    if (ssl == NULL)
21711
        return WOLFSSL_FAILURE;
21712
21713
    return ssl->options.handShakeState == NULL_STATE;
21714
}
21715
21716
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
21717
{
21718
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
21719
21720
    if (ssl == NULL)
21721
        return WOLFSSL_FAILURE;
21722
21723
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
21724
        return ssl->options.connectState > CONNECT_BEGIN &&
21725
            ssl->options.connectState < SECOND_REPLY_DONE;
21726
    }
21727
21728
    return ssl->options.acceptState > ACCEPT_BEGIN &&
21729
        ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
21730
}
21731
21732
#if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
21733
/* Expected return values from implementations of OpenSSL ticket key callback.
21734
 */
21735
#define TICKET_KEY_CB_RET_FAILURE    (-1)
21736
#define TICKET_KEY_CB_RET_NOT_FOUND   0
21737
#define TICKET_KEY_CB_RET_OK          1
21738
#define TICKET_KEY_CB_RET_RENEW       2
21739
21740
/* Implementation of session ticket encryption/decryption using OpenSSL
21741
 * callback to initialize the cipher and HMAC.
21742
 *
21743
 * ssl           The SSL/TLS object.
21744
 * keyName       The key name - used to identify the key to be used.
21745
 * iv            The IV to use.
21746
 * mac           The MAC of the encrypted data.
21747
 * enc           Encrypt ticket.
21748
 * encTicket     The ticket data.
21749
 * encTicketLen  The length of the ticket data.
21750
 * encLen        The encrypted/decrypted ticket length - output length.
21751
 * ctx           Ignored. Application specific data.
21752
 * returns WOLFSSL_TICKET_RET_OK to indicate success,
21753
 *         WOLFSSL_TICKET_RET_CREATE if a new ticket is required and
21754
 *         WOLFSSL_TICKET_RET_FATAL on error.
21755
 */
21756
static int wolfSSL_TicketKeyCb(WOLFSSL* ssl,
21757
        unsigned char keyName[WOLFSSL_TICKET_NAME_SZ],
21758
        unsigned char iv[WOLFSSL_TICKET_IV_SZ],
21759
        unsigned char mac[WOLFSSL_TICKET_MAC_SZ],
21760
        int enc, unsigned char* encTicket,
21761
        int encTicketLen, int* encLen, void* ctx)
21762
{
21763
    byte                    digest[WC_MAX_DIGEST_SIZE];
21764
    WC_DECLARE_VAR(evpCtx, WOLFSSL_EVP_CIPHER_CTX, 1, 0);
21765
    WOLFSSL_HMAC_CTX        hmacCtx;
21766
    unsigned int            mdSz = 0;
21767
    int                     len = 0;
21768
    int                     ret = WOLFSSL_TICKET_RET_FATAL;
21769
    int                     res;
21770
    int                     totalSz = 0;
21771
21772
    (void)ctx;
21773
21774
    WOLFSSL_ENTER("wolfSSL_TicketKeyCb");
21775
21776
    if (ssl == NULL || ssl->ctx == NULL || ssl->ctx->ticketEncWrapCb == NULL) {
21777
        WOLFSSL_MSG("Bad parameter");
21778
        return WOLFSSL_TICKET_RET_FATAL;
21779
    }
21780
21781
#ifdef WOLFSSL_SMALL_STACK
21782
    evpCtx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC(sizeof(*evpCtx), ssl->heap,
21783
                                               DYNAMIC_TYPE_TMP_BUFFER);
21784
    if (evpCtx == NULL) {
21785
        WOLFSSL_MSG("out of memory");
21786
        return WOLFSSL_TICKET_RET_FATAL;
21787
    }
21788
#endif
21789
21790
    /* Initialize the cipher and HMAC. */
21791
    wolfSSL_EVP_CIPHER_CTX_init(evpCtx);
21792
    if (wolfSSL_HMAC_CTX_Init(&hmacCtx) != WOLFSSL_SUCCESS) {
21793
        WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init error");
21794
        WC_FREE_VAR_EX(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
21795
        return WOLFSSL_TICKET_RET_FATAL;
21796
    }
21797
    res = ssl->ctx->ticketEncWrapCb(ssl, keyName,
21798
            iv, evpCtx, &hmacCtx, enc);
21799
    if (res != TICKET_KEY_CB_RET_OK && res != TICKET_KEY_CB_RET_RENEW) {
21800
        WOLFSSL_MSG("Ticket callback error");
21801
        ret = WOLFSSL_TICKET_RET_FATAL;
21802
        goto end;
21803
    }
21804
21805
    if (wolfSSL_HMAC_size(&hmacCtx) > WOLFSSL_TICKET_MAC_SZ) {
21806
        WOLFSSL_MSG("Ticket cipher MAC size error");
21807
        goto end;
21808
    }
21809
21810
    if (enc)
21811
    {
21812
        /* Encrypt in place. */
21813
        if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
21814
                                      encTicket, encTicketLen))
21815
            goto end;
21816
        totalSz = len;
21817
        if (totalSz > *encLen)
21818
            goto end;
21819
        if (!wolfSSL_EVP_EncryptFinal(evpCtx, &encTicket[len], &len))
21820
            goto end;
21821
        /* Total length of encrypted data. */
21822
        totalSz += len;
21823
        if (totalSz > *encLen)
21824
            goto end;
21825
21826
        /* HMAC the encrypted data into the parameter 'mac'. */
21827
        if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, totalSz))
21828
            goto end;
21829
        if (!wolfSSL_HMAC_Final(&hmacCtx, mac, &mdSz))
21830
            goto end;
21831
    }
21832
    else
21833
    {
21834
        /* HMAC the encrypted data and compare it to the passed in data. */
21835
        if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, encTicketLen))
21836
            goto end;
21837
        if (!wolfSSL_HMAC_Final(&hmacCtx, digest, &mdSz))
21838
            goto end;
21839
        if (XMEMCMP(mac, digest, mdSz) != 0)
21840
            goto end;
21841
21842
        /* Decrypt the ticket data in place. */
21843
        if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len,
21844
                                      encTicket, encTicketLen))
21845
            goto end;
21846
        totalSz = len;
21847
        if (totalSz > encTicketLen)
21848
            goto end;
21849
        if (!wolfSSL_EVP_DecryptFinal(evpCtx, &encTicket[len], &len))
21850
            goto end;
21851
        /* Total length of decrypted data. */
21852
        totalSz += len;
21853
        if (totalSz > encTicketLen)
21854
            goto end;
21855
    }
21856
    *encLen = totalSz;
21857
21858
    if (res == TICKET_KEY_CB_RET_RENEW && !IsAtLeastTLSv1_3(ssl->version)
21859
            && !enc)
21860
        ret = WOLFSSL_TICKET_RET_CREATE;
21861
    else
21862
        ret = WOLFSSL_TICKET_RET_OK;
21863
end:
21864
21865
    (void)wc_HmacFree(&hmacCtx.hmac);
21866
    (void)wolfSSL_EVP_CIPHER_CTX_cleanup(evpCtx);
21867
21868
    WC_FREE_VAR_EX(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
21869
21870
    return ret;
21871
}
21872
21873
/* Set the callback to use when encrypting/decrypting tickets.
21874
 *
21875
 * ctx  The SSL/TLS context object.
21876
 * cb   The OpenSSL session ticket callback.
21877
 * returns WOLFSSL_SUCCESS to indicate success.
21878
 */
21879
int wolfSSL_CTX_set_tlsext_ticket_key_cb(WOLFSSL_CTX *ctx, ticketCompatCb cb)
21880
{
21881
21882
    /* Set the ticket encryption callback to be a wrapper around OpenSSL
21883
     * callback.
21884
     */
21885
    ctx->ticketEncCb = wolfSSL_TicketKeyCb;
21886
    ctx->ticketEncWrapCb = cb;
21887
21888
    return WOLFSSL_SUCCESS;
21889
}
21890
21891
#endif /* HAVE_SESSION_TICKET */
21892
21893
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
21894
    OPENSSL_EXTRA || HAVE_LIGHTY */
21895
21896
#if defined(HAVE_SESSION_TICKET) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \
21897
    !defined(NO_WOLFSSL_SERVER)
21898
/* Serialize the session ticket encryption keys.
21899
 *
21900
 * @param [in]  ctx     SSL/TLS context object.
21901
 * @param [in]  keys    Buffer to hold session ticket keys.
21902
 * @param [in]  keylen  Length of buffer.
21903
 * @return  WOLFSSL_SUCCESS on success.
21904
 * @return  WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
21905
 *          correct length.
21906
 */
21907
long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
21908
     unsigned char *keys, int keylen)
21909
{
21910
    if (ctx == NULL || keys == NULL) {
21911
        return WOLFSSL_FAILURE;
21912
    }
21913
    if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
21914
        return WOLFSSL_FAILURE;
21915
    }
21916
21917
    XMEMCPY(keys, ctx->ticketKeyCtx.name, WOLFSSL_TICKET_NAME_SZ);
21918
    keys += WOLFSSL_TICKET_NAME_SZ;
21919
    XMEMCPY(keys, ctx->ticketKeyCtx.key[0], WOLFSSL_TICKET_KEY_SZ);
21920
    keys += WOLFSSL_TICKET_KEY_SZ;
21921
    XMEMCPY(keys, ctx->ticketKeyCtx.key[1], WOLFSSL_TICKET_KEY_SZ);
21922
    keys += WOLFSSL_TICKET_KEY_SZ;
21923
    c32toa(ctx->ticketKeyCtx.expirary[0], keys);
21924
    keys += OPAQUE32_LEN;
21925
    c32toa(ctx->ticketKeyCtx.expirary[1], keys);
21926
21927
    return WOLFSSL_SUCCESS;
21928
}
21929
21930
/* Deserialize the session ticket encryption keys.
21931
 *
21932
 * @param [in]  ctx     SSL/TLS context object.
21933
 * @param [in]  keys    Session ticket keys.
21934
 * @param [in]  keylen  Length of data.
21935
 * @return  WOLFSSL_SUCCESS on success.
21936
 * @return  WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the
21937
 *          correct length.
21938
 */
21939
long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx,
21940
     const void *keys_vp, int keylen)
21941
{
21942
    const byte* keys = (const byte*)keys_vp;
21943
    if (ctx == NULL || keys == NULL) {
21944
        return WOLFSSL_FAILURE;
21945
    }
21946
    if (keylen != WOLFSSL_TICKET_KEYS_SZ) {
21947
        return WOLFSSL_FAILURE;
21948
    }
21949
21950
    XMEMCPY(ctx->ticketKeyCtx.name, keys, WOLFSSL_TICKET_NAME_SZ);
21951
    keys += WOLFSSL_TICKET_NAME_SZ;
21952
    XMEMCPY(ctx->ticketKeyCtx.key[0], keys, WOLFSSL_TICKET_KEY_SZ);
21953
    keys += WOLFSSL_TICKET_KEY_SZ;
21954
    XMEMCPY(ctx->ticketKeyCtx.key[1], keys, WOLFSSL_TICKET_KEY_SZ);
21955
    keys += WOLFSSL_TICKET_KEY_SZ;
21956
    ato32(keys, &ctx->ticketKeyCtx.expirary[0]);
21957
    keys += OPAQUE32_LEN;
21958
    ato32(keys, &ctx->ticketKeyCtx.expirary[1]);
21959
21960
    return WOLFSSL_SUCCESS;
21961
}
21962
#endif
21963
21964
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
21965
#ifdef HAVE_OCSP
21966
/* Not an OpenSSL API. */
21967
int wolfSSL_get_ocsp_response(WOLFSSL* ssl, byte** response)
21968
{
21969
    *response = ssl->ocspCsrResp[0].buffer;
21970
    return ssl->ocspCsrResp[0].length;
21971
}
21972
21973
/* Not an OpenSSL API. */
21974
char* wolfSSL_get_ocsp_url(WOLFSSL* ssl)
21975
{
21976
    return ssl->url;
21977
}
21978
21979
/* Not an OpenSSL API. */
21980
int wolfSSL_set_ocsp_url(WOLFSSL* ssl, char* url)
21981
{
21982
    if (ssl == NULL)
21983
        return WOLFSSL_FAILURE;
21984
21985
    ssl->url = url;
21986
    return WOLFSSL_SUCCESS;
21987
}
21988
#endif /* OCSP */
21989
#endif /* OPENSSL_ALL || WOLFSSL_NGINX  || WOLFSSL_HAPROXY */
21990
21991
#if defined(HAVE_OCSP) && !defined(NO_ASN_TIME)
21992
int wolfSSL_get_ocsp_producedDate(
21993
    WOLFSSL *ssl,
21994
    byte *producedDate,
21995
    size_t producedDate_space,
21996
    int *producedDateFormat)
21997
{
21998
    if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) &&
21999
        (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME))
22000
        return BAD_FUNC_ARG;
22001
22002
    if ((producedDate == NULL) || (producedDateFormat == NULL))
22003
        return BAD_FUNC_ARG;
22004
22005
    if (XSTRLEN((char *)ssl->ocspProducedDate) >= producedDate_space)
22006
        return BUFFER_E;
22007
22008
    XSTRNCPY((char *)producedDate, (const char *)ssl->ocspProducedDate,
22009
        producedDate_space);
22010
    *producedDateFormat = ssl->ocspProducedDateFormat;
22011
22012
    return 0;
22013
}
22014
22015
int wolfSSL_get_ocsp_producedDate_tm(WOLFSSL *ssl, struct tm *produced_tm) {
22016
    int idx = 0;
22017
22018
    if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) &&
22019
        (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME))
22020
        return BAD_FUNC_ARG;
22021
22022
    if (produced_tm == NULL)
22023
        return BAD_FUNC_ARG;
22024
22025
    if (ExtractDate(ssl->ocspProducedDate,
22026
            (unsigned char)ssl->ocspProducedDateFormat, produced_tm, &idx,
22027
            MAX_DATE_SZ))
22028
        return 0;
22029
    else
22030
        return ASN_PARSE_E;
22031
}
22032
#endif
22033
22034
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
22035
        || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
22036
int wolfSSL_CTX_get_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb* cb)
22037
{
22038
    if (ctx == NULL || ctx->cm == NULL || cb == NULL)
22039
        return WOLFSSL_FAILURE;
22040
22041
#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
22042
                               || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
22043
    if (ctx->cm->ocsp_stapling == NULL)
22044
        return WOLFSSL_FAILURE;
22045
22046
    *cb = ctx->cm->ocsp_stapling->statusCb;
22047
#else
22048
    (void)cb;
22049
    *cb = NULL;
22050
#endif
22051
22052
    return WOLFSSL_SUCCESS;
22053
22054
}
22055
22056
int wolfSSL_CTX_set_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb cb)
22057
{
22058
    if (ctx == NULL || ctx->cm == NULL)
22059
        return WOLFSSL_FAILURE;
22060
22061
#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
22062
                               || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
22063
    /* Ensure stapling is on for callback to be used. */
22064
    wolfSSL_CTX_EnableOCSPStapling(ctx);
22065
22066
    if (ctx->cm->ocsp_stapling == NULL)
22067
        return WOLFSSL_FAILURE;
22068
22069
    ctx->cm->ocsp_stapling->statusCb = cb;
22070
#else
22071
    (void)cb;
22072
#endif
22073
22074
    return WOLFSSL_SUCCESS;
22075
}
22076
22077
long wolfSSL_CTX_set_tlsext_status_arg(WOLFSSL_CTX* ctx, void* arg)
22078
{
22079
    if (ctx == NULL || ctx->cm == NULL)
22080
        return WOLFSSL_FAILURE;
22081
22082
#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
22083
                               || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
22084
    /* Ensure stapling is on for callback to be used. */
22085
    wolfSSL_CTX_EnableOCSPStapling(ctx);
22086
22087
    if (ctx->cm->ocsp_stapling == NULL)
22088
        return WOLFSSL_FAILURE;
22089
22090
    ctx->cm->ocsp_stapling->statusCbArg = arg;
22091
#else
22092
    (void)arg;
22093
#endif
22094
22095
    return WOLFSSL_SUCCESS;
22096
}
22097
22098
long wolfSSL_get_tlsext_status_ocsp_resp(WOLFSSL *ssl, unsigned char **resp)
22099
{
22100
    if (ssl == NULL || resp == NULL)
22101
        return 0;
22102
22103
    *resp = ssl->ocspCsrResp[0].buffer;
22104
    return (long)ssl->ocspCsrResp[0].length;
22105
}
22106
22107
long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *ssl, unsigned char *resp,
22108
    int len)
22109
{
22110
    return wolfSSL_set_tlsext_status_ocsp_resp_multi(ssl, resp, len, 0);
22111
}
22112
22113
int wolfSSL_set_tlsext_status_ocsp_resp_multi(WOLFSSL* ssl, unsigned char *resp,
22114
        int len, word32 idx)
22115
{
22116
    if (ssl == NULL || idx >= XELEM_CNT(ssl->ocspCsrResp) || len < 0)
22117
        return WOLFSSL_FAILURE;
22118
    if (!((resp == NULL) ^ (len > 0)))
22119
        return WOLFSSL_FAILURE;
22120
22121
    XFREE(ssl->ocspCsrResp[idx].buffer, NULL, 0);
22122
    ssl->ocspCsrResp[idx].buffer = resp;
22123
    ssl->ocspCsrResp[idx].length = (word32)len;
22124
22125
    return WOLFSSL_SUCCESS;
22126
}
22127
22128
void wolfSSL_CTX_set_ocsp_status_verify_cb(WOLFSSL_CTX* ctx,
22129
        ocspVerifyStatusCb cb, void* cbArg)
22130
{
22131
    if (ctx != NULL) {
22132
        ctx->ocspStatusVerifyCb = cb;
22133
        ctx->ocspStatusVerifyCbArg = cbArg;
22134
    }
22135
}
22136
#endif
22137
22138
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
22139
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
22140
int wolfSSL_CTX_get_extra_chain_certs(WOLFSSL_CTX* ctx,
22141
    WOLF_STACK_OF(X509)** chain)
22142
{
22143
    word32         idx;
22144
    word32         length;
22145
    WOLFSSL_STACK* node;
22146
    WOLFSSL_STACK* last = NULL;
22147
22148
    if (ctx == NULL || chain == NULL) {
22149
        chain = NULL;
22150
        return WOLFSSL_FAILURE;
22151
    }
22152
    if (ctx->x509Chain != NULL) {
22153
        *chain = ctx->x509Chain;
22154
        return WOLFSSL_SUCCESS;
22155
    }
22156
22157
    /* If there are no chains then success! */
22158
    *chain = NULL;
22159
    if (ctx->certChain == NULL || ctx->certChain->length == 0) {
22160
        return WOLFSSL_SUCCESS;
22161
    }
22162
22163
    /* Create a new stack of WOLFSSL_X509 object from chain buffer. */
22164
    for (idx = 0; idx < ctx->certChain->length; ) {
22165
        node = wolfSSL_sk_X509_new_null();
22166
        if (node == NULL)
22167
            return WOLFSSL_FAILURE;
22168
        node->next = NULL;
22169
22170
        /* 3 byte length | X509 DER data */
22171
        ato24(ctx->certChain->buffer + idx, &length);
22172
        idx += 3;
22173
22174
        /* Create a new X509 from DER encoded data. */
22175
        node->data.x509 = wolfSSL_X509_d2i_ex(NULL,
22176
            ctx->certChain->buffer + idx, (int)length, ctx->heap);
22177
        if (node->data.x509 == NULL) {
22178
            XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL);
22179
            /* Return as much of the chain as we created. */
22180
            ctx->x509Chain = *chain;
22181
            return WOLFSSL_FAILURE;
22182
        }
22183
        idx += length;
22184
22185
        /* Add object to the end of the stack. */
22186
        if (last == NULL) {
22187
            node->num = 1;
22188
            *chain = node;
22189
        }
22190
        else {
22191
            (*chain)->num++;
22192
            last->next = node;
22193
        }
22194
22195
        last = node;
22196
    }
22197
22198
    ctx->x509Chain = *chain;
22199
22200
    return WOLFSSL_SUCCESS;
22201
}
22202
22203
int wolfSSL_CTX_get0_chain_certs(WOLFSSL_CTX *ctx,
22204
        WOLF_STACK_OF(WOLFSSL_X509) **sk)
22205
{
22206
    WOLFSSL_ENTER("wolfSSL_CTX_get0_chain_certs");
22207
    if (ctx == NULL || sk == NULL) {
22208
        WOLFSSL_MSG("Bad parameter");
22209
        return WOLFSSL_FAILURE;
22210
    }
22211
22212
    /* This function should return ctx->x509Chain if it is populated, otherwise
22213
       it should be populated from ctx->certChain.  This matches the behavior of
22214
       wolfSSL_CTX_get_extra_chain_certs, so it is used directly. */
22215
    return wolfSSL_CTX_get_extra_chain_certs(ctx, sk);
22216
}
22217
22218
#ifdef KEEP_OUR_CERT
22219
int wolfSSL_get0_chain_certs(WOLFSSL *ssl,
22220
        WOLF_STACK_OF(WOLFSSL_X509) **sk)
22221
{
22222
    WOLFSSL_ENTER("wolfSSL_get0_chain_certs");
22223
    if (ssl == NULL || sk == NULL) {
22224
        WOLFSSL_MSG("Bad parameter");
22225
        return WOLFSSL_FAILURE;
22226
    }
22227
    *sk = ssl->ourCertChain;
22228
    return WOLFSSL_SUCCESS;
22229
}
22230
#endif
22231
22232
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
22233
{
22234
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
22235
22236
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
22237
}
22238
22239
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
22240
22241
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
22242
    defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \
22243
    defined(WOLFSSL_QUIC)
22244
#ifdef HAVE_ALPN
22245
void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data,
22246
                                unsigned int *len)
22247
{
22248
    word16 nameLen = 0;
22249
22250
    if (ssl != NULL && data != NULL && len != NULL) {
22251
        TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen);
22252
        *len = nameLen;
22253
    }
22254
}
22255
22256
int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen,
22257
                              const unsigned char *in, unsigned int inLen,
22258
                              const unsigned char *clientNames,
22259
                              unsigned int clientLen)
22260
{
22261
    unsigned int i, j;
22262
    byte lenIn, lenClient;
22263
22264
    if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL)
22265
        return WOLFSSL_NPN_UNSUPPORTED;
22266
22267
    for (i = 0; i < inLen; i += lenIn) {
22268
        lenIn = in[i++];
22269
        for (j = 0; j < clientLen; j += lenClient) {
22270
            lenClient = clientNames[j++];
22271
22272
            if (lenIn != lenClient)
22273
                continue;
22274
22275
            if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) {
22276
                *out = (unsigned char *)(in + i);
22277
                *outLen = lenIn;
22278
                return WOLFSSL_NPN_NEGOTIATED;
22279
            }
22280
        }
22281
    }
22282
22283
    *out = (unsigned char *)clientNames + 1;
22284
    *outLen = clientNames[0];
22285
    return WOLFSSL_NPN_NO_OVERLAP;
22286
}
22287
22288
void wolfSSL_set_alpn_select_cb(WOLFSSL *ssl,
22289
                                int (*cb) (WOLFSSL *ssl,
22290
                                           const unsigned char **out,
22291
                                           unsigned char *outlen,
22292
                                           const unsigned char *in,
22293
                                           unsigned int inlen,
22294
                                           void *arg), void *arg)
22295
{
22296
    if (ssl != NULL) {
22297
        ssl->alpnSelect = cb;
22298
        ssl->alpnSelectArg = arg;
22299
    }
22300
}
22301
22302
void wolfSSL_CTX_set_alpn_select_cb(WOLFSSL_CTX *ctx,
22303
                                    int (*cb) (WOLFSSL *ssl,
22304
                                               const unsigned char **out,
22305
                                               unsigned char *outlen,
22306
                                               const unsigned char *in,
22307
                                               unsigned int inlen,
22308
                                               void *arg), void *arg)
22309
{
22310
    if (ctx != NULL) {
22311
        ctx->alpnSelect = cb;
22312
        ctx->alpnSelectArg = arg;
22313
    }
22314
}
22315
22316
void wolfSSL_CTX_set_next_protos_advertised_cb(WOLFSSL_CTX *s,
22317
                                           int (*cb) (WOLFSSL *ssl,
22318
                                                      const unsigned char
22319
                                                      **out,
22320
                                                      unsigned int *outlen,
22321
                                                      void *arg), void *arg)
22322
{
22323
    (void)s;
22324
    (void)cb;
22325
    (void)arg;
22326
    WOLFSSL_STUB("wolfSSL_CTX_set_next_protos_advertised_cb");
22327
}
22328
22329
void wolfSSL_CTX_set_next_proto_select_cb(WOLFSSL_CTX *s,
22330
                                      int (*cb) (WOLFSSL *ssl,
22331
                                                 unsigned char **out,
22332
                                                 unsigned char *outlen,
22333
                                                 const unsigned char *in,
22334
                                                 unsigned int inlen,
22335
                                                 void *arg), void *arg)
22336
{
22337
    (void)s;
22338
    (void)cb;
22339
    (void)arg;
22340
    WOLFSSL_STUB("wolfSSL_CTX_set_next_proto_select_cb");
22341
}
22342
22343
void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s,
22344
    const unsigned char **data, unsigned *len)
22345
{
22346
    (void)s;
22347
    (void)data;
22348
    (void)len;
22349
    WOLFSSL_STUB("wolfSSL_get0_next_proto_negotiated");
22350
}
22351
#endif /* HAVE_ALPN */
22352
22353
#endif /* WOLFSSL_NGINX  / WOLFSSL_HAPROXY */
22354
22355
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
22356
int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id)
22357
{
22358
    int ret = 0;
22359
22360
    WOLFSSL_ENTER("wolfSSL_curve_is_disabled");
22361
    WOLFSSL_MSG_EX("wolfSSL_curve_is_disabled checking for %d", curve_id);
22362
22363
    /* (curve_id >= WOLFSSL_FFDHE_START) - DH parameters are never disabled. */
22364
    if (curve_id < WOLFSSL_FFDHE_START) {
22365
        if (curve_id > WOLFSSL_ECC_MAX_AVAIL) {
22366
            WOLFSSL_MSG("Curve id out of supported range");
22367
            /* Disabled if not in valid range. */
22368
            ret = 1;
22369
        }
22370
        else if (curve_id >= 32) {
22371
            /* 0 is for invalid and 1-14 aren't used otherwise. */
22372
            ret = (ssl->disabledCurves & (1U << (curve_id - 32))) != 0;
22373
        }
22374
        else {
22375
            ret = (ssl->disabledCurves & (1U << curve_id)) != 0;
22376
        }
22377
    }
22378
22379
    WOLFSSL_LEAVE("wolfSSL_curve_is_disabled", ret);
22380
    return ret;
22381
}
22382
22383
#if (defined(HAVE_ECC) || \
22384
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
22385
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
22386
22387
const WOLF_EC_NIST_NAME kNistCurves[] = {
22388
#ifdef HAVE_ECC
22389
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
22390
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
22391
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
22392
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
22393
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
22394
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
22395
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
22396
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
22397
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
22398
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224R1},
22399
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
22400
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
22401
     WOLFSSL_ECC_BRAINPOOLP256R1},
22402
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
22403
     WOLFSSL_ECC_BRAINPOOLP384R1},
22404
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
22405
     WOLFSSL_ECC_BRAINPOOLP512R1},
22406
#endif
22407
#ifdef HAVE_CURVE25519
22408
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
22409
#endif
22410
#ifdef HAVE_CURVE448
22411
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
22412
#endif
22413
#ifdef WOLFSSL_HAVE_MLKEM
22414
#ifndef WOLFSSL_NO_ML_KEM
22415
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
22416
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
22417
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
22418
#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC)
22419
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
22420
     WOLFSSL_SECP256R1MLKEM512},
22421
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
22422
     WOLFSSL_SECP384R1MLKEM768},
22423
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
22424
     WOLFSSL_SECP256R1MLKEM768},
22425
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
22426
     WOLFSSL_SECP521R1MLKEM1024},
22427
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
22428
     WOLFSSL_SECP384R1MLKEM1024},
22429
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
22430
     WOLFSSL_X25519MLKEM512},
22431
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
22432
     WOLFSSL_X448MLKEM768},
22433
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
22434
     WOLFSSL_X25519MLKEM768},
22435
#endif
22436
#endif /* !WOLFSSL_NO_ML_KEM */
22437
#ifdef WOLFSSL_MLKEM_KYBER
22438
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
22439
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
22440
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
22441
#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC)
22442
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
22443
     WOLFSSL_P256_KYBER_LEVEL1},
22444
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
22445
     WOLFSSL_P384_KYBER_LEVEL3},
22446
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
22447
     WOLFSSL_P256_KYBER_LEVEL3},
22448
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
22449
     WOLFSSL_P521_KYBER_LEVEL5},
22450
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
22451
     WOLFSSL_X25519_KYBER_LEVEL1},
22452
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
22453
     WOLFSSL_X448_KYBER_LEVEL3},
22454
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
22455
     WOLFSSL_X25519_KYBER_LEVEL3},
22456
#endif
22457
#endif /* WOLFSSL_MLKEM_KYBER */
22458
#endif /* WOLFSSL_HAVE_MLKEM */
22459
#ifdef WOLFSSL_SM2
22460
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
22461
#endif
22462
#ifdef HAVE_ECC
22463
    /* Alternative curve names */
22464
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
22465
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
22466
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
22467
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
22468
#endif
22469
#ifdef WOLFSSL_SM2
22470
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
22471
#endif
22472
    {0, NULL, 0, 0},
22473
};
22474
22475
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
22476
        byte curves_only)
22477
{
22478
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
22479
    word16 curve;
22480
    word32 disabled;
22481
    char name[MAX_CURVE_NAME_SZ];
22482
    byte groups_len = 0;
22483
#ifdef WOLFSSL_SMALL_STACK
22484
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
22485
    int *groups;
22486
#else
22487
    int groups[WOLFSSL_MAX_GROUP_COUNT];
22488
#endif
22489
    const WOLF_EC_NIST_NAME* nist_name;
22490
22491
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
22492
        DYNAMIC_TYPE_TMP_BUFFER,
22493
    {
22494
        ret=MEMORY_E;
22495
        goto leave;
22496
    });
22497
22498
    for (idx = 1; names[idx-1] != '\0'; idx++) {
22499
        if (names[idx] != ':' && names[idx] != '\0')
22500
            continue;
22501
22502
        len = idx - start;
22503
        if (len > MAX_CURVE_NAME_SZ - 1)
22504
            goto leave;
22505
22506
        XMEMCPY(name, names + start, (size_t)len);
22507
        name[len] = 0;
22508
        curve = WOLFSSL_NAMED_GROUP_INVALID;
22509
22510
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
22511
            if (len == nist_name->name_len &&
22512
                    XSTRNCMP(name, nist_name->name, (size_t)len) == 0) {
22513
                curve = nist_name->curve;
22514
                break;
22515
            }
22516
        }
22517
22518
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
22519
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
22520
            int   nret;
22521
            const ecc_set_type *eccSet;
22522
22523
            nret = wc_ecc_get_curve_idx_from_name(name);
22524
            if (nret < 0) {
22525
                WOLFSSL_MSG("Could not find name in set");
22526
                goto leave;
22527
            }
22528
22529
            eccSet = wc_ecc_get_curve_params(ret);
22530
            if (eccSet == NULL) {
22531
                WOLFSSL_MSG("NULL set returned");
22532
                goto leave;
22533
            }
22534
22535
            curve = GetCurveByOID((int)eccSet->oidSum);
22536
        #else
22537
            WOLFSSL_MSG("API not present to search farther using name");
22538
            goto leave;
22539
        #endif
22540
        }
22541
22542
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
22543
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
22544
            WOLFSSL_MSG("curve value is not supported");
22545
            goto leave;
22546
        }
22547
22548
        for (i = 0; i < groups_len; ++i) {
22549
            if (groups[i] == curve) {
22550
                /* silently drop duplicates */
22551
                break;
22552
            }
22553
        }
22554
        if (i >= groups_len) {
22555
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
22556
                WOLFSSL_MSG_EX("setting %d or more supported "
22557
                               "curves is not permitted", groups_len);
22558
                goto leave;
22559
            }
22560
            groups[groups_len++] = (int)curve;
22561
        }
22562
22563
        start = idx + 1;
22564
    }
22565
22566
    /* Disable all curves so that only the ones the user wants are enabled. */
22567
    disabled = 0xFFFFFFFFUL;
22568
    for (i = 0; i < groups_len; ++i) {
22569
        /* Switch the bit to off and therefore is enabled. */
22570
        curve = (word16)groups[i];
22571
        if (curve >= 64) {
22572
            WC_DO_NOTHING;
22573
        }
22574
        else if (curve >= 32) {
22575
            /* 0 is for invalid and 1-14 aren't used otherwise. */
22576
            disabled &= ~(1U << (curve - 32));
22577
        }
22578
        else {
22579
            disabled &= ~(1U << curve);
22580
        }
22581
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
22582
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
22583
        /* using the wolfSSL API to set the groups, this will populate
22584
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
22585
         * The order in (ssl|ctx)->groups will then be respected
22586
         * when TLSX_KEY_SHARE needs to be established */
22587
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
22588
                        != WOLFSSL_SUCCESS)
22589
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
22590
                           != WOLFSSL_SUCCESS)) {
22591
            WOLFSSL_MSG("Unable to set supported curve");
22592
            goto leave;
22593
        }
22594
    #elif !defined(NO_WOLFSSL_CLIENT)
22595
        /* set the supported curve so client TLS extension contains only the
22596
         * desired curves */
22597
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
22598
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
22599
                           != WOLFSSL_SUCCESS)) {
22600
            WOLFSSL_MSG("Unable to set supported curve");
22601
            goto leave;
22602
        }
22603
    #endif
22604
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
22605
    }
22606
22607
    if (ssl != NULL)
22608
        ssl->disabledCurves = disabled;
22609
    else if (ctx != NULL)
22610
        ctx->disabledCurves = disabled;
22611
    ret = WOLFSSL_SUCCESS;
22612
22613
leave:
22614
#ifdef WOLFSSL_SMALL_STACK
22615
    if (groups)
22616
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
22617
#endif
22618
    return ret;
22619
}
22620
22621
int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names)
22622
{
22623
    WOLFSSL_ENTER("wolfSSL_CTX_set1_curves_list");
22624
    if (ctx == NULL || names == NULL) {
22625
        WOLFSSL_MSG("ctx or names was NULL");
22626
        return WOLFSSL_FAILURE;
22627
    }
22628
    return set_curves_list(NULL, ctx, names, 1);
22629
}
22630
22631
int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names)
22632
{
22633
    WOLFSSL_ENTER("wolfSSL_set1_curves_list");
22634
    if (ssl == NULL || names == NULL) {
22635
        WOLFSSL_MSG("ssl or names was NULL");
22636
        return WOLFSSL_FAILURE;
22637
    }
22638
    return set_curves_list(ssl, NULL, names, 1);
22639
}
22640
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
22641
#endif /* OPENSSL_EXTRA || HAVE_CURL */
22642
22643
22644
#ifdef OPENSSL_EXTRA
22645
/* Sets a callback for when sending and receiving protocol messages.
22646
 * This callback is copied to all WOLFSSL objects created from the ctx.
22647
 *
22648
 * ctx WOLFSSL_CTX structure to set callback in
22649
 * cb  callback to use
22650
 *
22651
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
22652
 */
22653
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
22654
{
22655
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
22656
    if (ctx == NULL) {
22657
        WOLFSSL_MSG("Null ctx passed in");
22658
        return WOLFSSL_FAILURE;
22659
    }
22660
22661
    ctx->protoMsgCb = cb;
22662
    return WOLFSSL_SUCCESS;
22663
}
22664
22665
22666
/* Sets a callback for when sending and receiving protocol messages.
22667
 *
22668
 * ssl WOLFSSL structure to set callback in
22669
 * cb  callback to use
22670
 *
22671
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
22672
 */
22673
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
22674
{
22675
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
22676
22677
    if (ssl == NULL) {
22678
        return WOLFSSL_FAILURE;
22679
    }
22680
22681
    if (cb != NULL) {
22682
        ssl->toInfoOn = 1;
22683
    }
22684
22685
    ssl->protoMsgCb = cb;
22686
    return WOLFSSL_SUCCESS;
22687
}
22688
22689
22690
/* set the user argument to pass to the msg callback when called
22691
 * return WOLFSSL_SUCCESS on success */
22692
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
22693
{
22694
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
22695
    if (ctx == NULL) {
22696
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
22697
        return WOLFSSL_FAILURE;
22698
    }
22699
22700
    ctx->protoMsgCtx = arg;
22701
    return WOLFSSL_SUCCESS;
22702
}
22703
22704
22705
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
22706
{
22707
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
22708
    if (ssl == NULL)
22709
        return WOLFSSL_FAILURE;
22710
22711
    ssl->protoMsgCtx = arg;
22712
    return WOLFSSL_SUCCESS;
22713
}
22714
22715
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
22716
    int line)
22717
{
22718
    void *ret;
22719
    (void)file;
22720
    (void)line;
22721
22722
    if (data == NULL || siz >= INT_MAX)
22723
        return NULL;
22724
22725
    ret = wolfSSL_OPENSSL_malloc(siz);
22726
    if (ret == NULL) {
22727
        return NULL;
22728
    }
22729
    return XMEMCPY(ret, data, siz);
22730
}
22731
22732
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
22733
{
22734
    if (ptr)
22735
        ForceZero(ptr, (word32)len);
22736
}
22737
22738
int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p,
22739
                            unsigned int p_len)
22740
{
22741
    WOLFSSL_ENTER("wolfSSL_CTX_set_alpn_protos");
22742
    if (ctx == NULL)
22743
        return BAD_FUNC_ARG;
22744
    if (ctx->alpn_cli_protos != NULL) {
22745
        XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL);
22746
    }
22747
22748
    ctx->alpn_cli_protos = (const unsigned char*)XMALLOC(p_len,
22749
        ctx->heap, DYNAMIC_TYPE_OPENSSL);
22750
    if (ctx->alpn_cli_protos == NULL) {
22751
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22752
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22753
         * the function reverses the return value convention.
22754
         */
22755
        return 1;
22756
#else
22757
        return WOLFSSL_FAILURE;
22758
#endif
22759
    }
22760
    XMEMCPY((void*)ctx->alpn_cli_protos, p, p_len);
22761
    ctx->alpn_cli_protos_len = p_len;
22762
22763
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22764
    /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22765
     * the function reverses the return value convention.
22766
     */
22767
    return 0;
22768
#else
22769
    return WOLFSSL_SUCCESS;
22770
#endif
22771
}
22772
22773
22774
#ifdef HAVE_ALPN
22775
#ifndef NO_BIO
22776
/* Sets the ALPN extension protos
22777
 *
22778
 * example format is
22779
 * unsigned char p[] = {
22780
 *      8, 'h', 't', 't', 'p', '/', '1', '.', '1'
22781
 * };
22782
 *
22783
 * returns WOLFSSL_SUCCESS on success */
22784
int wolfSSL_set_alpn_protos(WOLFSSL* ssl,
22785
        const unsigned char* p, unsigned int p_len)
22786
{
22787
    char* pt = NULL;
22788
    unsigned int ptIdx;
22789
    unsigned int sz;
22790
    unsigned int idx = 0;
22791
    int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH;
22792
    int ret;
22793
22794
    WOLFSSL_ENTER("wolfSSL_set_alpn_protos");
22795
22796
    if (ssl == NULL || p_len <= 1) {
22797
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22798
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22799
         * the function reverses the return value convention.
22800
         */
22801
        return 1;
22802
#else
22803
        return WOLFSSL_FAILURE;
22804
#endif
22805
    }
22806
22807
    /* Replacing leading number with trailing ',' and adding '\0'. */
22808
    pt = (char*)XMALLOC(p_len + 1, ssl->heap, DYNAMIC_TYPE_OPENSSL);
22809
    if (pt == NULL) {
22810
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22811
        /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22812
         * the function reverses the return value convention.
22813
         */
22814
        return 1;
22815
#else
22816
        return WOLFSSL_FAILURE;
22817
#endif
22818
    }
22819
22820
    ptIdx = 0;
22821
    /* convert into comma separated list */
22822
    while (idx < p_len - 1) {
22823
        unsigned int i;
22824
22825
        sz = p[idx++];
22826
        if (idx + sz > p_len) {
22827
            WOLFSSL_MSG("Bad list format");
22828
            XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL);
22829
    #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22830
            /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22831
             * the function reverses the return value convention.
22832
             */
22833
            return 1;
22834
    #else
22835
            return WOLFSSL_FAILURE;
22836
    #endif
22837
        }
22838
        if (sz > 0) {
22839
            for (i = 0; i < sz; i++) {
22840
                pt[ptIdx++] = p[idx++];
22841
            }
22842
            if (idx < p_len - 1) {
22843
                pt[ptIdx++] = ',';
22844
            }
22845
        }
22846
    }
22847
    pt[ptIdx++] = '\0';
22848
22849
    /* clears out all current ALPN extensions set */
22850
    TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap);
22851
22852
    ret = wolfSSL_UseALPN(ssl, pt, ptIdx, (byte)alpn_opt);
22853
    XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL);
22854
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
22855
    /* 0 on success in OpenSSL, non-0 on failure in OpenSSL
22856
     * the function reverses the return value convention.
22857
     */
22858
    if (ret != WOLFSSL_SUCCESS)
22859
        return 1;
22860
    return 0;
22861
#else
22862
    if (ret != WOLFSSL_SUCCESS)
22863
        return WOLFSSL_FAILURE;
22864
    return WOLFSSL_SUCCESS;
22865
#endif
22866
}
22867
#endif /* !NO_BIO */
22868
#endif /* HAVE_ALPN */
22869
#endif /* OPENSSL_EXTRA */
22870
22871
#if defined(OPENSSL_EXTRA)
22872
22873
#ifndef NO_BIO
22874
#define WOLFSSL_BIO_INCLUDED
22875
#include "src/bio.c"
22876
#endif
22877
22878
word32 nid2oid(int nid, int grp)
22879
{
22880
    /* get OID type */
22881
    switch (grp) {
22882
        /* oidHashType */
22883
        case oidHashType:
22884
            switch (nid) {
22885
            #ifdef WOLFSSL_MD2
22886
                case WC_NID_md2:
22887
                    return MD2h;
22888
            #endif
22889
            #ifndef NO_MD5
22890
                case WC_NID_md5:
22891
                    return MD5h;
22892
            #endif
22893
            #ifndef NO_SHA
22894
                case WC_NID_sha1:
22895
                    return SHAh;
22896
            #endif
22897
                case WC_NID_sha224:
22898
                    return SHA224h;
22899
            #ifndef NO_SHA256
22900
                case WC_NID_sha256:
22901
                    return SHA256h;
22902
            #endif
22903
            #ifdef WOLFSSL_SHA384
22904
                case WC_NID_sha384:
22905
                    return SHA384h;
22906
            #endif
22907
            #ifdef WOLFSSL_SHA512
22908
                case WC_NID_sha512:
22909
                    return SHA512h;
22910
            #endif
22911
            #ifndef WOLFSSL_NOSHA3_224
22912
                case WC_NID_sha3_224:
22913
                    return SHA3_224h;
22914
            #endif
22915
            #ifndef WOLFSSL_NOSHA3_256
22916
                case WC_NID_sha3_256:
22917
                    return SHA3_256h;
22918
            #endif
22919
            #ifndef WOLFSSL_NOSHA3_384
22920
                case WC_NID_sha3_384:
22921
                    return SHA3_384h;
22922
            #endif
22923
            #ifndef WOLFSSL_NOSHA3_512
22924
                case WC_NID_sha3_512:
22925
                    return SHA3_512h;
22926
            #endif
22927
            }
22928
            break;
22929
22930
        /*  oidSigType */
22931
        case oidSigType:
22932
            switch (nid) {
22933
            #ifndef NO_DSA
22934
                case WC_NID_dsaWithSHA1:
22935
                    return CTC_SHAwDSA;
22936
                case WC_NID_dsa_with_SHA256:
22937
                    return CTC_SHA256wDSA;
22938
            #endif /* NO_DSA */
22939
            #ifndef NO_RSA
22940
                case WC_NID_md2WithRSAEncryption:
22941
                    return CTC_MD2wRSA;
22942
                case WC_NID_md5WithRSAEncryption:
22943
                    return CTC_MD5wRSA;
22944
                case WC_NID_sha1WithRSAEncryption:
22945
                    return CTC_SHAwRSA;
22946
                case WC_NID_sha224WithRSAEncryption:
22947
                    return CTC_SHA224wRSA;
22948
                case WC_NID_sha256WithRSAEncryption:
22949
                    return CTC_SHA256wRSA;
22950
                case WC_NID_sha384WithRSAEncryption:
22951
                    return CTC_SHA384wRSA;
22952
                case WC_NID_sha512WithRSAEncryption:
22953
                    return CTC_SHA512wRSA;
22954
                #ifdef WOLFSSL_SHA3
22955
                case WC_NID_RSA_SHA3_224:
22956
                    return CTC_SHA3_224wRSA;
22957
                case WC_NID_RSA_SHA3_256:
22958
                    return CTC_SHA3_256wRSA;
22959
                case WC_NID_RSA_SHA3_384:
22960
                    return CTC_SHA3_384wRSA;
22961
                case WC_NID_RSA_SHA3_512:
22962
                    return CTC_SHA3_512wRSA;
22963
                #endif
22964
            #endif /* NO_RSA */
22965
            #ifdef HAVE_ECC
22966
                case WC_NID_ecdsa_with_SHA1:
22967
                    return CTC_SHAwECDSA;
22968
                case WC_NID_ecdsa_with_SHA224:
22969
                    return CTC_SHA224wECDSA;
22970
                case WC_NID_ecdsa_with_SHA256:
22971
                    return CTC_SHA256wECDSA;
22972
                case WC_NID_ecdsa_with_SHA384:
22973
                    return CTC_SHA384wECDSA;
22974
                case WC_NID_ecdsa_with_SHA512:
22975
                    return CTC_SHA512wECDSA;
22976
                #ifdef WOLFSSL_SHA3
22977
                case WC_NID_ecdsa_with_SHA3_224:
22978
                    return CTC_SHA3_224wECDSA;
22979
                case WC_NID_ecdsa_with_SHA3_256:
22980
                    return CTC_SHA3_256wECDSA;
22981
                case WC_NID_ecdsa_with_SHA3_384:
22982
                    return CTC_SHA3_384wECDSA;
22983
                case WC_NID_ecdsa_with_SHA3_512:
22984
                    return CTC_SHA3_512wECDSA;
22985
                #endif
22986
            #endif /* HAVE_ECC */
22987
            }
22988
            break;
22989
22990
        /* oidKeyType */
22991
        case oidKeyType:
22992
            switch (nid) {
22993
            #ifndef NO_DSA
22994
                case WC_NID_dsa:
22995
                    return DSAk;
22996
            #endif /* NO_DSA */
22997
            #ifndef NO_RSA
22998
                case WC_NID_rsaEncryption:
22999
                    return RSAk;
23000
            #endif /* NO_RSA */
23001
            #ifdef HAVE_ECC
23002
                case WC_NID_X9_62_id_ecPublicKey:
23003
                    return ECDSAk;
23004
            #endif /* HAVE_ECC */
23005
            }
23006
            break;
23007
23008
23009
    #ifdef HAVE_ECC
23010
        case oidCurveType:
23011
            switch (nid) {
23012
            case WC_NID_X9_62_prime192v1:
23013
                return ECC_SECP192R1_OID;
23014
            case WC_NID_X9_62_prime192v2:
23015
                return ECC_PRIME192V2_OID;
23016
            case WC_NID_X9_62_prime192v3:
23017
                return ECC_PRIME192V3_OID;
23018
            case WC_NID_X9_62_prime239v1:
23019
                return ECC_PRIME239V1_OID;
23020
            case WC_NID_X9_62_prime239v2:
23021
                return ECC_PRIME239V2_OID;
23022
            case WC_NID_X9_62_prime239v3:
23023
                return ECC_PRIME239V3_OID;
23024
            case WC_NID_X9_62_prime256v1:
23025
                return ECC_SECP256R1_OID;
23026
            case WC_NID_secp112r1:
23027
                return ECC_SECP112R1_OID;
23028
            case WC_NID_secp112r2:
23029
                return ECC_SECP112R2_OID;
23030
            case WC_NID_secp128r1:
23031
                return ECC_SECP128R1_OID;
23032
            case WC_NID_secp128r2:
23033
                return ECC_SECP128R2_OID;
23034
            case WC_NID_secp160r1:
23035
                return ECC_SECP160R1_OID;
23036
            case WC_NID_secp160r2:
23037
                return ECC_SECP160R2_OID;
23038
            case WC_NID_secp224r1:
23039
                return ECC_SECP224R1_OID;
23040
            case WC_NID_secp384r1:
23041
                return ECC_SECP384R1_OID;
23042
            case WC_NID_secp521r1:
23043
                return ECC_SECP521R1_OID;
23044
            case WC_NID_secp160k1:
23045
                return ECC_SECP160K1_OID;
23046
            case WC_NID_secp192k1:
23047
                return ECC_SECP192K1_OID;
23048
            case WC_NID_secp224k1:
23049
                return ECC_SECP224K1_OID;
23050
            case WC_NID_secp256k1:
23051
                return ECC_SECP256K1_OID;
23052
            case WC_NID_brainpoolP160r1:
23053
                return ECC_BRAINPOOLP160R1_OID;
23054
            case WC_NID_brainpoolP192r1:
23055
                return ECC_BRAINPOOLP192R1_OID;
23056
            case WC_NID_brainpoolP224r1:
23057
                return ECC_BRAINPOOLP224R1_OID;
23058
            case WC_NID_brainpoolP256r1:
23059
                return ECC_BRAINPOOLP256R1_OID;
23060
            case WC_NID_brainpoolP320r1:
23061
                return ECC_BRAINPOOLP320R1_OID;
23062
            case WC_NID_brainpoolP384r1:
23063
                return ECC_BRAINPOOLP384R1_OID;
23064
            case WC_NID_brainpoolP512r1:
23065
                return ECC_BRAINPOOLP512R1_OID;
23066
            }
23067
            break;
23068
    #endif /* HAVE_ECC */
23069
23070
        /* oidBlkType */
23071
        case oidBlkType:
23072
            switch (nid) {
23073
            #ifdef WOLFSSL_AES_128
23074
                case AES128CBCb:
23075
                    return AES128CBCb;
23076
            #endif
23077
            #ifdef WOLFSSL_AES_192
23078
                case AES192CBCb:
23079
                    return AES192CBCb;
23080
            #endif
23081
            #ifdef WOLFSSL_AES_256
23082
                case AES256CBCb:
23083
                    return AES256CBCb;
23084
            #endif
23085
            #ifndef NO_DES3
23086
                case WC_NID_des:
23087
                    return DESb;
23088
                case WC_NID_des3:
23089
                    return DES3b;
23090
            #endif
23091
            }
23092
            break;
23093
23094
    #ifdef HAVE_OCSP
23095
        case oidOcspType:
23096
            switch (nid) {
23097
                case WC_NID_id_pkix_OCSP_basic:
23098
                    return OCSP_BASIC_OID;
23099
                case OCSP_NONCE_OID:
23100
                    return OCSP_NONCE_OID;
23101
            }
23102
            break;
23103
    #endif /* HAVE_OCSP */
23104
23105
        /* oidCertExtType */
23106
        case oidCertExtType:
23107
            switch (nid) {
23108
                case WC_NID_basic_constraints:
23109
                    return BASIC_CA_OID;
23110
                case WC_NID_subject_alt_name:
23111
                    return ALT_NAMES_OID;
23112
                case WC_NID_crl_distribution_points:
23113
                    return CRL_DIST_OID;
23114
                case WC_NID_info_access:
23115
                    return AUTH_INFO_OID;
23116
                case WC_NID_authority_key_identifier:
23117
                    return AUTH_KEY_OID;
23118
                case WC_NID_subject_key_identifier:
23119
                    return SUBJ_KEY_OID;
23120
                case WC_NID_inhibit_any_policy:
23121
                    return INHIBIT_ANY_OID;
23122
                case WC_NID_key_usage:
23123
                    return KEY_USAGE_OID;
23124
                case WC_NID_name_constraints:
23125
                    return NAME_CONS_OID;
23126
                case WC_NID_certificate_policies:
23127
                    return CERT_POLICY_OID;
23128
                case WC_NID_ext_key_usage:
23129
                    return EXT_KEY_USAGE_OID;
23130
            }
23131
            break;
23132
23133
        /* oidCertAuthInfoType */
23134
        case oidCertAuthInfoType:
23135
            switch (nid) {
23136
                case WC_NID_ad_OCSP:
23137
                    return AIA_OCSP_OID;
23138
                case WC_NID_ad_ca_issuers:
23139
                    return AIA_CA_ISSUER_OID;
23140
            }
23141
            break;
23142
23143
        /* oidCertPolicyType */
23144
        case oidCertPolicyType:
23145
            switch (nid) {
23146
                case WC_NID_any_policy:
23147
                    return CP_ANY_OID;
23148
            }
23149
            break;
23150
23151
        /* oidCertAltNameType */
23152
        case oidCertAltNameType:
23153
            switch (nid) {
23154
                case WC_NID_hw_name_oid:
23155
                    return HW_NAME_OID;
23156
            }
23157
            break;
23158
23159
        /* oidCertKeyUseType */
23160
        case oidCertKeyUseType:
23161
            switch (nid) {
23162
                case WC_NID_anyExtendedKeyUsage:
23163
                    return EKU_ANY_OID;
23164
                case EKU_SERVER_AUTH_OID:
23165
                    return EKU_SERVER_AUTH_OID;
23166
                case EKU_CLIENT_AUTH_OID:
23167
                    return EKU_CLIENT_AUTH_OID;
23168
                case EKU_OCSP_SIGN_OID:
23169
                    return EKU_OCSP_SIGN_OID;
23170
            }
23171
            break;
23172
23173
        /* oidKdfType */
23174
        case oidKdfType:
23175
            switch (nid) {
23176
                case PBKDF2_OID:
23177
                    return PBKDF2_OID;
23178
            }
23179
            break;
23180
23181
        /* oidPBEType */
23182
        case oidPBEType:
23183
            switch (nid) {
23184
                case PBE_SHA1_RC4_128:
23185
                    return PBE_SHA1_RC4_128;
23186
                case PBE_SHA1_DES:
23187
                    return PBE_SHA1_DES;
23188
                case PBE_SHA1_DES3:
23189
                    return PBE_SHA1_DES3;
23190
            }
23191
            break;
23192
23193
        /* oidKeyWrapType */
23194
        case oidKeyWrapType:
23195
            switch (nid) {
23196
            #ifdef WOLFSSL_AES_128
23197
                case AES128_WRAP:
23198
                    return AES128_WRAP;
23199
            #endif
23200
            #ifdef WOLFSSL_AES_192
23201
                case AES192_WRAP:
23202
                    return AES192_WRAP;
23203
            #endif
23204
            #ifdef WOLFSSL_AES_256
23205
                case AES256_WRAP:
23206
                    return AES256_WRAP;
23207
            #endif
23208
            }
23209
            break;
23210
23211
        /* oidCmsKeyAgreeType */
23212
        case oidCmsKeyAgreeType:
23213
            switch (nid) {
23214
                #ifndef NO_SHA
23215
                case dhSinglePass_stdDH_sha1kdf_scheme:
23216
                    return dhSinglePass_stdDH_sha1kdf_scheme;
23217
                #endif
23218
                #ifdef WOLFSSL_SHA224
23219
                case dhSinglePass_stdDH_sha224kdf_scheme:
23220
                    return dhSinglePass_stdDH_sha224kdf_scheme;
23221
                #endif
23222
                #ifndef NO_SHA256
23223
                case dhSinglePass_stdDH_sha256kdf_scheme:
23224
                    return dhSinglePass_stdDH_sha256kdf_scheme;
23225
                #endif
23226
                #ifdef WOLFSSL_SHA384
23227
                case dhSinglePass_stdDH_sha384kdf_scheme:
23228
                    return dhSinglePass_stdDH_sha384kdf_scheme;
23229
                #endif
23230
                #ifdef WOLFSSL_SHA512
23231
                case dhSinglePass_stdDH_sha512kdf_scheme:
23232
                    return dhSinglePass_stdDH_sha512kdf_scheme;
23233
                #endif
23234
            }
23235
            break;
23236
23237
        /* oidCmsKeyAgreeType */
23238
    #ifdef WOLFSSL_CERT_REQ
23239
        case oidCsrAttrType:
23240
            switch (nid) {
23241
                case WC_NID_pkcs9_contentType:
23242
                    return PKCS9_CONTENT_TYPE_OID;
23243
                case WC_NID_pkcs9_challengePassword:
23244
                    return CHALLENGE_PASSWORD_OID;
23245
                case WC_NID_serialNumber:
23246
                    return SERIAL_NUMBER_OID;
23247
                case WC_NID_userId:
23248
                    return USER_ID_OID;
23249
                case WC_NID_surname:
23250
                    return SURNAME_OID;
23251
            }
23252
            break;
23253
    #endif
23254
23255
        default:
23256
            WOLFSSL_MSG("NID not in table");
23257
            /* MSVC warns without the cast */
23258
            return (word32)-1;
23259
    }
23260
23261
    /* MSVC warns without the cast */
23262
    return (word32)-1;
23263
}
23264
23265
int oid2nid(word32 oid, int grp)
23266
{
23267
    size_t i;
23268
    /* get OID type */
23269
    switch (grp) {
23270
        /* oidHashType */
23271
        case oidHashType:
23272
            switch (oid) {
23273
            #ifdef WOLFSSL_MD2
23274
                case MD2h:
23275
                    return WC_NID_md2;
23276
            #endif
23277
            #ifndef NO_MD5
23278
                case MD5h:
23279
                    return WC_NID_md5;
23280
            #endif
23281
            #ifndef NO_SHA
23282
                case SHAh:
23283
                    return WC_NID_sha1;
23284
            #endif
23285
                case SHA224h:
23286
                    return WC_NID_sha224;
23287
            #ifndef NO_SHA256
23288
                case SHA256h:
23289
                    return WC_NID_sha256;
23290
            #endif
23291
            #ifdef WOLFSSL_SHA384
23292
                case SHA384h:
23293
                    return WC_NID_sha384;
23294
            #endif
23295
            #ifdef WOLFSSL_SHA512
23296
                case SHA512h:
23297
                    return WC_NID_sha512;
23298
            #endif
23299
            }
23300
            break;
23301
23302
        /*  oidSigType */
23303
        case oidSigType:
23304
            switch (oid) {
23305
            #ifndef NO_DSA
23306
                case CTC_SHAwDSA:
23307
                    return WC_NID_dsaWithSHA1;
23308
                case CTC_SHA256wDSA:
23309
                    return WC_NID_dsa_with_SHA256;
23310
            #endif /* NO_DSA */
23311
            #ifndef NO_RSA
23312
                case CTC_MD2wRSA:
23313
                    return WC_NID_md2WithRSAEncryption;
23314
                case CTC_MD5wRSA:
23315
                    return WC_NID_md5WithRSAEncryption;
23316
                case CTC_SHAwRSA:
23317
                    return WC_NID_sha1WithRSAEncryption;
23318
                case CTC_SHA224wRSA:
23319
                    return WC_NID_sha224WithRSAEncryption;
23320
                case CTC_SHA256wRSA:
23321
                    return WC_NID_sha256WithRSAEncryption;
23322
                case CTC_SHA384wRSA:
23323
                    return WC_NID_sha384WithRSAEncryption;
23324
                case CTC_SHA512wRSA:
23325
                    return WC_NID_sha512WithRSAEncryption;
23326
                #ifdef WOLFSSL_SHA3
23327
                case CTC_SHA3_224wRSA:
23328
                    return WC_NID_RSA_SHA3_224;
23329
                case CTC_SHA3_256wRSA:
23330
                    return WC_NID_RSA_SHA3_256;
23331
                case CTC_SHA3_384wRSA:
23332
                    return WC_NID_RSA_SHA3_384;
23333
                case CTC_SHA3_512wRSA:
23334
                    return WC_NID_RSA_SHA3_512;
23335
                #endif
23336
                #ifdef WC_RSA_PSS
23337
                case CTC_RSASSAPSS:
23338
                    return WC_NID_rsassaPss;
23339
                #endif
23340
            #endif /* NO_RSA */
23341
            #ifdef HAVE_ECC
23342
                case CTC_SHAwECDSA:
23343
                    return WC_NID_ecdsa_with_SHA1;
23344
                case CTC_SHA224wECDSA:
23345
                    return WC_NID_ecdsa_with_SHA224;
23346
                case CTC_SHA256wECDSA:
23347
                    return WC_NID_ecdsa_with_SHA256;
23348
                case CTC_SHA384wECDSA:
23349
                    return WC_NID_ecdsa_with_SHA384;
23350
                case CTC_SHA512wECDSA:
23351
                    return WC_NID_ecdsa_with_SHA512;
23352
                #ifdef WOLFSSL_SHA3
23353
                case CTC_SHA3_224wECDSA:
23354
                    return WC_NID_ecdsa_with_SHA3_224;
23355
                case CTC_SHA3_256wECDSA:
23356
                    return WC_NID_ecdsa_with_SHA3_256;
23357
                case CTC_SHA3_384wECDSA:
23358
                    return WC_NID_ecdsa_with_SHA3_384;
23359
                case CTC_SHA3_512wECDSA:
23360
                    return WC_NID_ecdsa_with_SHA3_512;
23361
                #endif
23362
            #endif /* HAVE_ECC */
23363
            }
23364
            break;
23365
23366
        /* oidKeyType */
23367
        case oidKeyType:
23368
            switch (oid) {
23369
            #ifndef NO_DSA
23370
                case DSAk:
23371
                    return WC_NID_dsa;
23372
            #endif /* NO_DSA */
23373
            #ifndef NO_RSA
23374
                case RSAk:
23375
                    return WC_NID_rsaEncryption;
23376
                #ifdef WC_RSA_PSS
23377
                case RSAPSSk:
23378
                    return WC_NID_rsassaPss;
23379
                #endif
23380
            #endif /* NO_RSA */
23381
            #ifdef HAVE_ECC
23382
                case ECDSAk:
23383
                    return WC_NID_X9_62_id_ecPublicKey;
23384
            #endif /* HAVE_ECC */
23385
            }
23386
            break;
23387
23388
23389
    #ifdef HAVE_ECC
23390
        case oidCurveType:
23391
            switch (oid) {
23392
            case ECC_SECP192R1_OID:
23393
                return WC_NID_X9_62_prime192v1;
23394
            case ECC_PRIME192V2_OID:
23395
                return WC_NID_X9_62_prime192v2;
23396
            case ECC_PRIME192V3_OID:
23397
                return WC_NID_X9_62_prime192v3;
23398
            case ECC_PRIME239V1_OID:
23399
                return WC_NID_X9_62_prime239v1;
23400
            case ECC_PRIME239V2_OID:
23401
                return WC_NID_X9_62_prime239v2;
23402
            case ECC_PRIME239V3_OID:
23403
                return WC_NID_X9_62_prime239v3;
23404
            case ECC_SECP256R1_OID:
23405
                return WC_NID_X9_62_prime256v1;
23406
            case ECC_SECP112R1_OID:
23407
                return WC_NID_secp112r1;
23408
            case ECC_SECP112R2_OID:
23409
                return WC_NID_secp112r2;
23410
            case ECC_SECP128R1_OID:
23411
                return WC_NID_secp128r1;
23412
            case ECC_SECP128R2_OID:
23413
                return WC_NID_secp128r2;
23414
            case ECC_SECP160R1_OID:
23415
                return WC_NID_secp160r1;
23416
            case ECC_SECP160R2_OID:
23417
                return WC_NID_secp160r2;
23418
            case ECC_SECP224R1_OID:
23419
                return WC_NID_secp224r1;
23420
            case ECC_SECP384R1_OID:
23421
                return WC_NID_secp384r1;
23422
            case ECC_SECP521R1_OID:
23423
                return WC_NID_secp521r1;
23424
            case ECC_SECP160K1_OID:
23425
                return WC_NID_secp160k1;
23426
            case ECC_SECP192K1_OID:
23427
                return WC_NID_secp192k1;
23428
            case ECC_SECP224K1_OID:
23429
                return WC_NID_secp224k1;
23430
            case ECC_SECP256K1_OID:
23431
                return WC_NID_secp256k1;
23432
            case ECC_BRAINPOOLP160R1_OID:
23433
                return WC_NID_brainpoolP160r1;
23434
            case ECC_BRAINPOOLP192R1_OID:
23435
                return WC_NID_brainpoolP192r1;
23436
            case ECC_BRAINPOOLP224R1_OID:
23437
                return WC_NID_brainpoolP224r1;
23438
            case ECC_BRAINPOOLP256R1_OID:
23439
                return WC_NID_brainpoolP256r1;
23440
            case ECC_BRAINPOOLP320R1_OID:
23441
                return WC_NID_brainpoolP320r1;
23442
            case ECC_BRAINPOOLP384R1_OID:
23443
                return WC_NID_brainpoolP384r1;
23444
            case ECC_BRAINPOOLP512R1_OID:
23445
                return WC_NID_brainpoolP512r1;
23446
            }
23447
            break;
23448
    #endif /* HAVE_ECC */
23449
23450
        /* oidBlkType */
23451
        case oidBlkType:
23452
            switch (oid) {
23453
            #ifdef WOLFSSL_AES_128
23454
                case AES128CBCb:
23455
                    return AES128CBCb;
23456
            #endif
23457
            #ifdef WOLFSSL_AES_192
23458
                case AES192CBCb:
23459
                    return AES192CBCb;
23460
            #endif
23461
            #ifdef WOLFSSL_AES_256
23462
                case AES256CBCb:
23463
                    return AES256CBCb;
23464
            #endif
23465
            #ifndef NO_DES3
23466
                case DESb:
23467
                    return WC_NID_des;
23468
                case DES3b:
23469
                    return WC_NID_des3;
23470
            #endif
23471
            }
23472
            break;
23473
23474
    #ifdef HAVE_OCSP
23475
        case oidOcspType:
23476
            switch (oid) {
23477
                case OCSP_BASIC_OID:
23478
                    return WC_NID_id_pkix_OCSP_basic;
23479
                case OCSP_NONCE_OID:
23480
                    return OCSP_NONCE_OID;
23481
            }
23482
            break;
23483
    #endif /* HAVE_OCSP */
23484
23485
        /* oidCertExtType */
23486
        case oidCertExtType:
23487
            switch (oid) {
23488
                case BASIC_CA_OID:
23489
                    return WC_NID_basic_constraints;
23490
                case ALT_NAMES_OID:
23491
                    return WC_NID_subject_alt_name;
23492
                case CRL_DIST_OID:
23493
                    return WC_NID_crl_distribution_points;
23494
                case AUTH_INFO_OID:
23495
                    return WC_NID_info_access;
23496
                case AUTH_KEY_OID:
23497
                    return WC_NID_authority_key_identifier;
23498
                case SUBJ_KEY_OID:
23499
                    return WC_NID_subject_key_identifier;
23500
                case INHIBIT_ANY_OID:
23501
                    return WC_NID_inhibit_any_policy;
23502
                case KEY_USAGE_OID:
23503
                    return WC_NID_key_usage;
23504
                case NAME_CONS_OID:
23505
                    return WC_NID_name_constraints;
23506
                case CERT_POLICY_OID:
23507
                    return WC_NID_certificate_policies;
23508
                case EXT_KEY_USAGE_OID:
23509
                    return WC_NID_ext_key_usage;
23510
            }
23511
            break;
23512
23513
        /* oidCertAuthInfoType */
23514
        case oidCertAuthInfoType:
23515
            switch (oid) {
23516
                case AIA_OCSP_OID:
23517
                    return WC_NID_ad_OCSP;
23518
                case AIA_CA_ISSUER_OID:
23519
                    return WC_NID_ad_ca_issuers;
23520
            }
23521
            break;
23522
23523
        /* oidCertPolicyType */
23524
        case oidCertPolicyType:
23525
            switch (oid) {
23526
                case CP_ANY_OID:
23527
                    return WC_NID_any_policy;
23528
            }
23529
            break;
23530
23531
        /* oidCertAltNameType */
23532
        case oidCertAltNameType:
23533
            switch (oid) {
23534
                case HW_NAME_OID:
23535
                    return WC_NID_hw_name_oid;
23536
            }
23537
            break;
23538
23539
        /* oidCertKeyUseType */
23540
        case oidCertKeyUseType:
23541
            switch (oid) {
23542
                case EKU_ANY_OID:
23543
                    return WC_NID_anyExtendedKeyUsage;
23544
                case EKU_SERVER_AUTH_OID:
23545
                    return EKU_SERVER_AUTH_OID;
23546
                case EKU_CLIENT_AUTH_OID:
23547
                    return EKU_CLIENT_AUTH_OID;
23548
                case EKU_OCSP_SIGN_OID:
23549
                    return EKU_OCSP_SIGN_OID;
23550
            }
23551
            break;
23552
23553
        /* oidKdfType */
23554
        case oidKdfType:
23555
            switch (oid) {
23556
                case PBKDF2_OID:
23557
                    return PBKDF2_OID;
23558
            }
23559
            break;
23560
23561
        /* oidPBEType */
23562
        case oidPBEType:
23563
            switch (oid) {
23564
                case PBE_SHA1_RC4_128:
23565
                    return PBE_SHA1_RC4_128;
23566
                case PBE_SHA1_DES:
23567
                    return PBE_SHA1_DES;
23568
                case PBE_SHA1_DES3:
23569
                    return PBE_SHA1_DES3;
23570
            }
23571
            break;
23572
23573
        /* oidKeyWrapType */
23574
        case oidKeyWrapType:
23575
            switch (oid) {
23576
            #ifdef WOLFSSL_AES_128
23577
                case AES128_WRAP:
23578
                    return AES128_WRAP;
23579
            #endif
23580
            #ifdef WOLFSSL_AES_192
23581
                case AES192_WRAP:
23582
                    return AES192_WRAP;
23583
            #endif
23584
            #ifdef WOLFSSL_AES_256
23585
                case AES256_WRAP:
23586
                    return AES256_WRAP;
23587
            #endif
23588
            }
23589
            break;
23590
23591
        /* oidCmsKeyAgreeType */
23592
        case oidCmsKeyAgreeType:
23593
            switch (oid) {
23594
                #ifndef NO_SHA
23595
                case dhSinglePass_stdDH_sha1kdf_scheme:
23596
                    return dhSinglePass_stdDH_sha1kdf_scheme;
23597
                #endif
23598
                #ifdef WOLFSSL_SHA224
23599
                case dhSinglePass_stdDH_sha224kdf_scheme:
23600
                    return dhSinglePass_stdDH_sha224kdf_scheme;
23601
                #endif
23602
                #ifndef NO_SHA256
23603
                case dhSinglePass_stdDH_sha256kdf_scheme:
23604
                    return dhSinglePass_stdDH_sha256kdf_scheme;
23605
                #endif
23606
                #ifdef WOLFSSL_SHA384
23607
                case dhSinglePass_stdDH_sha384kdf_scheme:
23608
                    return dhSinglePass_stdDH_sha384kdf_scheme;
23609
                #endif
23610
                #ifdef WOLFSSL_SHA512
23611
                case dhSinglePass_stdDH_sha512kdf_scheme:
23612
                    return dhSinglePass_stdDH_sha512kdf_scheme;
23613
                #endif
23614
            }
23615
            break;
23616
23617
#ifdef WOLFSSL_CERT_REQ
23618
        case oidCsrAttrType:
23619
            switch (oid) {
23620
                case PKCS9_CONTENT_TYPE_OID:
23621
                    return WC_NID_pkcs9_contentType;
23622
                case CHALLENGE_PASSWORD_OID:
23623
                    return WC_NID_pkcs9_challengePassword;
23624
                case SERIAL_NUMBER_OID:
23625
                    return WC_NID_serialNumber;
23626
                case USER_ID_OID:
23627
                    return WC_NID_userId;
23628
            }
23629
            break;
23630
#endif
23631
23632
        default:
23633
            WOLFSSL_MSG("OID not in table");
23634
    }
23635
    /* If not found in above switch then try the table */
23636
    for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) {
23637
        if (wolfssl_object_info[i].id == (int)oid) {
23638
            return wolfssl_object_info[i].nid;
23639
        }
23640
    }
23641
23642
    return WOLFSSL_FATAL_ERROR;
23643
}
23644
23645
/* frees all nodes in the current threads error queue
23646
 *
23647
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
23648
 *     current threads queue will be free'd.
23649
 */
23650
void wolfSSL_ERR_remove_state(unsigned long id)
23651
{
23652
    WOLFSSL_ENTER("wolfSSL_ERR_remove_state");
23653
    (void)id;
23654
    if (wc_ERR_remove_state() != 0) {
23655
        WOLFSSL_MSG("Error with removing the state");
23656
    }
23657
}
23658
23659
#endif /* OPENSSL_EXTRA */
23660
23661
#ifdef OPENSSL_ALL
23662
23663
#if !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8)
23664
23665
static int bio_get_data(WOLFSSL_BIO* bio, byte** data)
23666
{
23667
    int ret = 0;
23668
    byte* mem = NULL;
23669
23670
    ret = wolfSSL_BIO_get_len(bio);
23671
    if (ret > 0) {
23672
        mem = (byte*)XMALLOC((size_t)ret, bio->heap, DYNAMIC_TYPE_OPENSSL);
23673
        if (mem == NULL) {
23674
            WOLFSSL_MSG("Memory error");
23675
            ret = MEMORY_E;
23676
        }
23677
        if (ret >= 0) {
23678
            if ((ret = wolfSSL_BIO_read(bio, mem, ret)) <= 0) {
23679
                XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL);
23680
                ret = MEMORY_E;
23681
                mem = NULL;
23682
            }
23683
        }
23684
    }
23685
23686
    *data = mem;
23687
23688
    return ret;
23689
}
23690
23691
/* DER data is PKCS#8 encrypted. */
23692
WOLFSSL_EVP_PKEY* wolfSSL_d2i_PKCS8PrivateKey_bio(WOLFSSL_BIO* bio,
23693
                                                  WOLFSSL_EVP_PKEY** pkey,
23694
                                                  wc_pem_password_cb* cb,
23695
                                                  void* ctx)
23696
{
23697
    int ret;
23698
    byte* der;
23699
    int len;
23700
    byte* p;
23701
    word32 algId;
23702
    WOLFSSL_EVP_PKEY* key;
23703
23704
    if ((len = bio_get_data(bio, &der)) < 0)
23705
        return NULL;
23706
23707
    if (cb != NULL) {
23708
        char password[NAME_SZ];
23709
        int passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx);
23710
        if (passwordSz < 0) {
23711
            XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
23712
            return NULL;
23713
        }
23714
    #ifdef WOLFSSL_CHECK_MEM_ZERO
23715
        wc_MemZero_Add("wolfSSL_d2i_PKCS8PrivateKey_bio password", password,
23716
            passwordSz);
23717
    #endif
23718
23719
        ret = ToTraditionalEnc(der, (word32)len, password, passwordSz, &algId);
23720
        if (ret < 0) {
23721
            XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
23722
            return NULL;
23723
        }
23724
23725
        ForceZero(password, (word32)passwordSz);
23726
    #ifdef WOLFSSL_CHECK_MEM_ZERO
23727
        wc_MemZero_Check(password, passwordSz);
23728
    #endif
23729
    }
23730
23731
    p = der;
23732
    key = wolfSSL_d2i_PrivateKey_EVP(pkey, &p, len);
23733
    XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL);
23734
    return key;
23735
}
23736
23737
#endif /* !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */
23738
23739
/* Detect which type of key it is before decoding. */
23740
WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey,
23741
                                             const unsigned char** pp,
23742
                                             long length)
23743
{
23744
    int ret;
23745
    WOLFSSL_EVP_PKEY* key = NULL;
23746
    const byte* der = *pp;
23747
    word32 idx = 0;
23748
    int len = 0;
23749
    int cnt = 0;
23750
    word32 algId;
23751
    word32 keyLen = (word32)length;
23752
23753
    /* Take off PKCS#8 wrapper if found. */
23754
    if ((len = ToTraditionalInline_ex(der, &idx, keyLen, &algId)) >= 0) {
23755
        der += idx;
23756
        keyLen = (word32)len;
23757
    }
23758
    idx = 0;
23759
    len = 0;
23760
23761
    /* Use the number of elements in the outer sequence to determine key type.
23762
     */
23763
    ret = GetSequence(der, &idx, &len, keyLen);
23764
    if (ret >= 0) {
23765
        word32 end = idx + (word32)len;
23766
        while (ret >= 0 && idx < end) {
23767
            /* Skip type */
23768
            idx++;
23769
            /* Get length and skip over - keeping count */
23770
            len = 0;
23771
            ret = GetLength(der, &idx, &len, keyLen);
23772
            if (ret >= 0) {
23773
                if (idx + (word32)len > end)
23774
                    ret = ASN_PARSE_E;
23775
                else {
23776
                    idx += (word32)len;
23777
                    cnt++;
23778
                }
23779
            }
23780
        }
23781
    }
23782
23783
    if (ret >= 0) {
23784
        int type;
23785
        /* ECC includes version, private[, curve][, public key] */
23786
        if (cnt >= 2 && cnt <= 4)
23787
            type = WC_EVP_PKEY_EC;
23788
        else
23789
            type = WC_EVP_PKEY_RSA;
23790
23791
        key = wolfSSL_d2i_PrivateKey(type, pkey, &der, keyLen);
23792
        *pp = der;
23793
    }
23794
23795
    return key;
23796
}
23797
#endif /* OPENSSL_ALL */
23798
23799
#ifdef WOLFSSL_STATIC_EPHEMERAL
23800
int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr)
23801
{
23802
    int ret;
23803
    word32 idx = 0;
23804
    DerBuffer* der = NULL;
23805
23806
    if (ssl == NULL || ssl->ctx == NULL || keyPtr == NULL) {
23807
        return BAD_FUNC_ARG;
23808
    }
23809
23810
#ifndef SINGLE_THREADED
23811
    if (!ssl->ctx->staticKELockInit) {
23812
        return BUFFER_E; /* no keys set */
23813
    }
23814
    ret = wc_LockMutex(&ssl->ctx->staticKELock);
23815
    if (ret != 0) {
23816
        return ret;
23817
    }
23818
#endif
23819
23820
    ret = BUFFER_E; /* set default error */
23821
    switch (keyAlgo) {
23822
    #ifndef NO_DH
23823
        case WC_PK_TYPE_DH:
23824
            if (ssl != NULL)
23825
                der = ssl->staticKE.dhKey;
23826
            if (der == NULL)
23827
                der = ssl->ctx->staticKE.dhKey;
23828
            if (der != NULL) {
23829
                DhKey* key = (DhKey*)keyPtr;
23830
                WOLFSSL_MSG("Using static DH key");
23831
                ret = wc_DhKeyDecode(der->buffer, &idx, key, der->length);
23832
            }
23833
            break;
23834
    #endif
23835
    #ifdef HAVE_ECC
23836
        case WC_PK_TYPE_ECDH:
23837
            if (ssl != NULL)
23838
                der = ssl->staticKE.ecKey;
23839
            if (der == NULL)
23840
                der = ssl->ctx->staticKE.ecKey;
23841
            if (der != NULL) {
23842
                ecc_key* key = (ecc_key*)keyPtr;
23843
                WOLFSSL_MSG("Using static ECDH key");
23844
                ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key,
23845
                    der->length);
23846
            }
23847
            break;
23848
    #endif
23849
    #ifdef HAVE_CURVE25519
23850
        case WC_PK_TYPE_CURVE25519:
23851
            if (ssl != NULL)
23852
                der = ssl->staticKE.x25519Key;
23853
            if (der == NULL)
23854
                der = ssl->ctx->staticKE.x25519Key;
23855
            if (der != NULL) {
23856
                curve25519_key* key = (curve25519_key*)keyPtr;
23857
                WOLFSSL_MSG("Using static X25519 key");
23858
23859
            #ifdef WOLFSSL_CURVE25519_BLINDING
23860
                ret = wc_curve25519_set_rng(key, ssl->rng);
23861
                if (ret == 0)
23862
            #endif
23863
                    ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key,
23864
                        der->length);
23865
            }
23866
            break;
23867
    #endif
23868
    #ifdef HAVE_CURVE448
23869
        case WC_PK_TYPE_CURVE448:
23870
            if (ssl != NULL)
23871
                der = ssl->staticKE.x448Key;
23872
            if (der == NULL)
23873
                der = ssl->ctx->staticKE.x448Key;
23874
            if (der != NULL) {
23875
                curve448_key* key = (curve448_key*)keyPtr;
23876
                WOLFSSL_MSG("Using static X448 key");
23877
                ret = wc_Curve448PrivateKeyDecode(der->buffer, &idx, key,
23878
                    der->length);
23879
            }
23880
            break;
23881
    #endif
23882
        default:
23883
            /* not supported */
23884
            ret = NOT_COMPILED_IN;
23885
            break;
23886
    }
23887
23888
#ifndef SINGLE_THREADED
23889
    wc_UnLockMutex(&ssl->ctx->staticKELock);
23890
#endif
23891
    return ret;
23892
}
23893
23894
static int SetStaticEphemeralKey(WOLFSSL_CTX* ctx,
23895
    StaticKeyExchangeInfo_t* staticKE, int keyAlgo, const char* key,
23896
    unsigned int keySz, int format, void* heap)
23897
{
23898
    int ret = 0;
23899
    DerBuffer* der = NULL;
23900
    byte* keyBuf = NULL;
23901
#ifndef NO_FILESYSTEM
23902
    const char* keyFile = NULL;
23903
#endif
23904
23905
    /* allow empty key to free buffer */
23906
    if (staticKE == NULL || (key == NULL && keySz > 0)) {
23907
        return BAD_FUNC_ARG;
23908
    }
23909
23910
    WOLFSSL_ENTER("SetStaticEphemeralKey");
23911
23912
    /* if just free'ing key then skip loading */
23913
    if (key != NULL) {
23914
    #ifndef NO_FILESYSTEM
23915
        /* load file from filesystem */
23916
        if (key != NULL && keySz == 0) {
23917
            size_t keyBufSz = 0;
23918
            keyFile = (const char*)key;
23919
            ret = wc_FileLoad(keyFile, &keyBuf, &keyBufSz, heap);
23920
            if (ret != 0) {
23921
                return ret;
23922
            }
23923
            keySz = (unsigned int)keyBufSz;
23924
        }
23925
        else
23926
    #endif
23927
        {
23928
            /* use as key buffer directly */
23929
            keyBuf = (byte*)key;
23930
        }
23931
23932
        if (format == WOLFSSL_FILETYPE_PEM) {
23933
        #ifdef WOLFSSL_PEM_TO_DER
23934
            int keyFormat = 0;
23935
            ret = PemToDer(keyBuf, keySz, PRIVATEKEY_TYPE, &der,
23936
                heap, NULL, &keyFormat);
23937
            /* auto detect key type */
23938
            if (ret == 0 && keyAlgo == WC_PK_TYPE_NONE) {
23939
                if (keyFormat == ECDSAk)
23940
                    keyAlgo = WC_PK_TYPE_ECDH;
23941
                else if (keyFormat == X25519k)
23942
                    keyAlgo = WC_PK_TYPE_CURVE25519;
23943
                else
23944
                    keyAlgo = WC_PK_TYPE_DH;
23945
            }
23946
        #else
23947
            ret = NOT_COMPILED_IN;
23948
        #endif
23949
        }
23950
        else {
23951
            /* Detect PK type (if required) */
23952
        #ifdef HAVE_ECC
23953
            if (keyAlgo == WC_PK_TYPE_NONE) {
23954
                word32 idx = 0;
23955
                ecc_key eccKey;
23956
                ret = wc_ecc_init_ex(&eccKey, heap, INVALID_DEVID);
23957
                if (ret == 0) {
23958
                    ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &eccKey, keySz);
23959
                    if (ret == 0)
23960
                        keyAlgo = WC_PK_TYPE_ECDH;
23961
                    wc_ecc_free(&eccKey);
23962
                }
23963
            }
23964
        #endif
23965
        #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
23966
            if (keyAlgo == WC_PK_TYPE_NONE) {
23967
                word32 idx = 0;
23968
                DhKey dhKey;
23969
                ret = wc_InitDhKey_ex(&dhKey, heap, INVALID_DEVID);
23970
                if (ret == 0) {
23971
                    ret = wc_DhKeyDecode(keyBuf, &idx, &dhKey, keySz);
23972
                    if (ret == 0)
23973
                        keyAlgo = WC_PK_TYPE_DH;
23974
                    wc_FreeDhKey(&dhKey);
23975
                }
23976
            }
23977
        #endif
23978
        #ifdef HAVE_CURVE25519
23979
            if (keyAlgo == WC_PK_TYPE_NONE) {
23980
                word32 idx = 0;
23981
                curve25519_key x25519Key;
23982
                ret = wc_curve25519_init_ex(&x25519Key, heap, INVALID_DEVID);
23983
                if (ret == 0) {
23984
                    ret = wc_Curve25519PrivateKeyDecode(keyBuf, &idx,
23985
                        &x25519Key, keySz);
23986
                    if (ret == 0)
23987
                        keyAlgo = WC_PK_TYPE_CURVE25519;
23988
                    wc_curve25519_free(&x25519Key);
23989
                }
23990
            }
23991
        #endif
23992
        #ifdef HAVE_CURVE448
23993
            if (keyAlgo == WC_PK_TYPE_NONE) {
23994
                word32 idx = 0;
23995
                curve448_key x448Key;
23996
                ret = wc_curve448_init(&x448Key);
23997
                if (ret == 0) {
23998
                    ret = wc_Curve448PrivateKeyDecode(keyBuf, &idx, &x448Key,
23999
                        keySz);
24000
                    if (ret == 0)
24001
                        keyAlgo = WC_PK_TYPE_CURVE448;
24002
                    wc_curve448_free(&x448Key);
24003
                }
24004
            }
24005
        #endif
24006
24007
            if (keyAlgo != WC_PK_TYPE_NONE) {
24008
                ret = AllocDer(&der, keySz, PRIVATEKEY_TYPE, heap);
24009
                if (ret == 0) {
24010
                    XMEMCPY(der->buffer, keyBuf, keySz);
24011
                }
24012
            }
24013
        }
24014
    }
24015
24016
#ifndef NO_FILESYSTEM
24017
    /* done with keyFile buffer */
24018
    if (keyFile && keyBuf) {
24019
        XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
24020
    }
24021
#endif
24022
24023
#ifndef SINGLE_THREADED
24024
    if (ret == 0 && !ctx->staticKELockInit) {
24025
        ret = wc_InitMutex(&ctx->staticKELock);
24026
        if (ret == 0) {
24027
            ctx->staticKELockInit = 1;
24028
        }
24029
    }
24030
#endif
24031
    if (ret == 0
24032
    #ifndef SINGLE_THREADED
24033
        && (ret = wc_LockMutex(&ctx->staticKELock)) == 0
24034
    #endif
24035
    ) {
24036
        switch (keyAlgo) {
24037
        #ifndef NO_DH
24038
            case WC_PK_TYPE_DH:
24039
                FreeDer(&staticKE->dhKey);
24040
                staticKE->dhKey = der; der = NULL;
24041
                break;
24042
        #endif
24043
        #ifdef HAVE_ECC
24044
            case WC_PK_TYPE_ECDH:
24045
                FreeDer(&staticKE->ecKey);
24046
                staticKE->ecKey = der; der = NULL;
24047
                break;
24048
        #endif
24049
        #ifdef HAVE_CURVE25519
24050
            case WC_PK_TYPE_CURVE25519:
24051
                FreeDer(&staticKE->x25519Key);
24052
                staticKE->x25519Key = der; der = NULL;
24053
                break;
24054
        #endif
24055
        #ifdef HAVE_CURVE448
24056
            case WC_PK_TYPE_CURVE448:
24057
                FreeDer(&staticKE->x448Key);
24058
                staticKE->x448Key = der; der = NULL;
24059
                break;
24060
        #endif
24061
            default:
24062
                /* not supported */
24063
                ret = NOT_COMPILED_IN;
24064
                break;
24065
        }
24066
24067
    #ifndef SINGLE_THREADED
24068
        wc_UnLockMutex(&ctx->staticKELock);
24069
    #endif
24070
    }
24071
24072
    if (ret != 0) {
24073
        FreeDer(&der);
24074
    }
24075
24076
    (void)ctx; /* not used for single threaded */
24077
24078
    WOLFSSL_LEAVE("SetStaticEphemeralKey", ret);
24079
24080
    return ret;
24081
}
24082
24083
int wolfSSL_CTX_set_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
24084
    const char* key, unsigned int keySz, int format)
24085
{
24086
    if (ctx == NULL) {
24087
        return BAD_FUNC_ARG;
24088
    }
24089
    return SetStaticEphemeralKey(ctx, &ctx->staticKE, keyAlgo,
24090
        key, keySz, format, ctx->heap);
24091
}
24092
int wolfSSL_set_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
24093
    const char* key, unsigned int keySz, int format)
24094
{
24095
    if (ssl == NULL || ssl->ctx == NULL) {
24096
        return BAD_FUNC_ARG;
24097
    }
24098
    return SetStaticEphemeralKey(ssl->ctx, &ssl->staticKE, keyAlgo,
24099
        key, keySz, format, ssl->heap);
24100
}
24101
24102
static int GetStaticEphemeralKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
24103
    int keyAlgo, const unsigned char** key, unsigned int* keySz)
24104
{
24105
    int ret = 0;
24106
    DerBuffer* der = NULL;
24107
24108
    if (key)   *key = NULL;
24109
    if (keySz) *keySz = 0;
24110
24111
#ifndef SINGLE_THREADED
24112
    if (ctx->staticKELockInit &&
24113
        (ret = wc_LockMutex(&ctx->staticKELock)) != 0) {
24114
        return ret;
24115
    }
24116
#endif
24117
24118
    switch (keyAlgo) {
24119
    #ifndef NO_DH
24120
        case WC_PK_TYPE_DH:
24121
            if (ssl != NULL)
24122
                der = ssl->staticKE.dhKey;
24123
            if (der == NULL)
24124
                der = ctx->staticKE.dhKey;
24125
            break;
24126
    #endif
24127
    #ifdef HAVE_ECC
24128
        case WC_PK_TYPE_ECDH:
24129
            if (ssl != NULL)
24130
                der = ssl->staticKE.ecKey;
24131
            if (der == NULL)
24132
                der = ctx->staticKE.ecKey;
24133
            break;
24134
    #endif
24135
    #ifdef HAVE_CURVE25519
24136
        case WC_PK_TYPE_CURVE25519:
24137
            if (ssl != NULL)
24138
                der = ssl->staticKE.x25519Key;
24139
            if (der == NULL)
24140
                der = ctx->staticKE.x25519Key;
24141
            break;
24142
    #endif
24143
    #ifdef HAVE_CURVE448
24144
        case WC_PK_TYPE_CURVE448:
24145
            if (ssl != NULL)
24146
                der = ssl->staticKE.x448Key;
24147
            if (der == NULL)
24148
                der = ctx->staticKE.x448Key;
24149
            break;
24150
    #endif
24151
        default:
24152
            /* not supported */
24153
            ret = NOT_COMPILED_IN;
24154
            break;
24155
    }
24156
24157
    if (der) {
24158
        if (key)
24159
            *key = der->buffer;
24160
        if (keySz)
24161
            *keySz = der->length;
24162
    }
24163
24164
#ifndef SINGLE_THREADED
24165
    wc_UnLockMutex(&ctx->staticKELock);
24166
#endif
24167
24168
    return ret;
24169
}
24170
24171
/* returns pointer to currently loaded static ephemeral as ASN.1 */
24172
/* this can be converted to PEM using wc_DerToPem */
24173
int wolfSSL_CTX_get_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo,
24174
    const unsigned char** key, unsigned int* keySz)
24175
{
24176
    if (ctx == NULL) {
24177
        return BAD_FUNC_ARG;
24178
    }
24179
24180
    return GetStaticEphemeralKey(ctx, NULL, keyAlgo, key, keySz);
24181
}
24182
int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo,
24183
    const unsigned char** key, unsigned int* keySz)
24184
{
24185
    if (ssl == NULL || ssl->ctx == NULL) {
24186
        return BAD_FUNC_ARG;
24187
    }
24188
24189
    return GetStaticEphemeralKey(ssl->ctx, ssl, keyAlgo, key, keySz);
24190
}
24191
24192
#endif /* WOLFSSL_STATIC_EPHEMERAL */
24193
24194
#if defined(OPENSSL_EXTRA)
24195
/* wolfSSL_THREADID_current is provided as a compat API with
24196
 * CRYPTO_THREADID_current to register current thread id into given id object.
24197
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
24198
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
24199
 * like as existing wolfSSL_THREADID_set_numeric.
24200
 */
24201
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
24202
{
24203
    (void)id;
24204
    return;
24205
}
24206
/* wolfSSL_THREADID_hash is provided as a compatible API with
24207
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
24208
 * specified thread id. However, CRYPTO_THREADID_hash API has been
24209
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
24210
 * This API only works as a stub to returns 0. This behavior is
24211
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
24212
 */
24213
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
24214
{
24215
    (void)id;
24216
    return 0UL;
24217
}
24218
/* wolfSSL_set_ecdh_auto is provided as compatible API with
24219
 * SSL_set_ecdh_auto to enable auto ecdh curve selection functionality.
24220
 * Since this functionality is enabled by default in wolfSSL,
24221
 * this API exists as a stub.
24222
 */
24223
int wolfSSL_set_ecdh_auto(WOLFSSL* ssl, int onoff)
24224
{
24225
    (void)ssl;
24226
    (void)onoff;
24227
    return WOLFSSL_SUCCESS;
24228
}
24229
/* wolfSSL_CTX_set_ecdh_auto is provided as compatible API with
24230
 * SSL_CTX_set_ecdh_auto to enable auto ecdh curve selection functionality.
24231
 * Since this functionality is enabled by default in wolfSSL,
24232
 * this API exists as a stub.
24233
 */
24234
int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff)
24235
{
24236
    (void)ctx;
24237
    (void)onoff;
24238
    return WOLFSSL_SUCCESS;
24239
}
24240
24241
/* wolfSSL_CTX_set_dh_auto is provided as compatible API with
24242
 * SSL_CTX_set_dh_auto to enable auto dh selection functionality.
24243
 * Since this functionality is enabled by default in wolfSSL,
24244
 * this API exists as a stub.
24245
 */
24246
int wolfSSL_CTX_set_dh_auto(WOLFSSL_CTX* ctx, int onoff)
24247
{
24248
    (void)ctx;
24249
    (void)onoff;
24250
    return WOLFSSL_SUCCESS;
24251
}
24252
24253
/**
24254
 * Set security level (wolfSSL doesn't support setting the security level).
24255
 *
24256
 * The security level can only be set through a system wide crypto-policy
24257
 * with wolfSSL_crypto_policy_enable().
24258
 *
24259
 * @param ctx  a pointer to WOLFSSL_CTX structure
24260
 * @param level security level
24261
 */
24262
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
24263
{
24264
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
24265
    (void)ctx;
24266
    (void)level;
24267
}
24268
24269
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
24270
{
24271
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
24272
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
24273
    if (ctx == NULL) {
24274
        return BAD_FUNC_ARG;
24275
    }
24276
24277
    return ctx->secLevel;
24278
    #else
24279
    (void)ctx;
24280
    return 0;
24281
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
24282
}
24283
24284
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
24285
/*
24286
 * This API accepts a user callback which puts key-log records into
24287
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
24288
 * each SSL object on its creation timing.
24289
 */
24290
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
24291
    wolfSSL_CTX_keylog_cb_func cb)
24292
{
24293
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
24294
    /* stores the callback into WOLFSSL_CTX */
24295
    if (ctx != NULL) {
24296
        ctx->keyLogCb = cb;
24297
    }
24298
}
24299
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
24300
    const WOLFSSL_CTX* ctx)
24301
{
24302
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
24303
    if (ctx != NULL)
24304
        return ctx->keyLogCb;
24305
    return NULL;
24306
}
24307
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
24308
24309
#endif /* OPENSSL_EXTRA */
24310
24311
#ifdef WOLFSSL_THREADED_CRYPT
24312
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
24313
{
24314
    ThreadCrypt* encrypt;
24315
24316
    if (ssl == NULL) {
24317
        return 0;
24318
    }
24319
24320
    encrypt = &ssl->buffers.encrypt[idx];
24321
    return (encrypt->avail == 0) && (encrypt->done == 0);
24322
}
24323
24324
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
24325
{
24326
    ThreadCrypt* encrypt;
24327
24328
    if (ssl == NULL) {
24329
        return 1;
24330
    }
24331
24332
    encrypt = &ssl->buffers.encrypt[idx];
24333
    return encrypt->stop;
24334
}
24335
24336
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
24337
{
24338
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
24339
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
24340
24341
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
24342
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
24343
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
24344
        word32 encSz = encrypt->buffer.length - encrypt->offset;
24345
24346
        ret =
24347
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
24348
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
24349
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
24350
              wc_AesGcmEncrypt_ex
24351
#else
24352
              wc_AesGcmEncrypt
24353
#endif
24354
              (encrypt->encrypt.aes,
24355
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
24356
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
24357
               encrypt->nonce, AESGCM_NONCE_SZ,
24358
               out + encSz - ssl->specs.aead_mac_size,
24359
               ssl->specs.aead_mac_size,
24360
               encrypt->additional, AEAD_AUTH_DATA_SZ);
24361
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
24362
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
24363
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
24364
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
24365
#endif
24366
        encrypt->done = 1;
24367
    }
24368
24369
    return ret;
24370
}
24371
24372
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
24373
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
24374
{
24375
    int ret = 0;
24376
24377
    if (ssl == NULL) {
24378
        ret = BAD_FUNC_ARG;
24379
    }
24380
    else {
24381
        ssl->buffers.encrypt[idx].signal = signal;
24382
        ssl->buffers.encrypt[idx].signalCtx = ctx;
24383
    }
24384
24385
    return ret;
24386
}
24387
#endif
24388
24389
24390
#ifndef NO_CERT
24391
#define WOLFSSL_X509_INCLUDED
24392
#include "src/x509.c"
24393
#endif
24394
24395
/*******************************************************************************
24396
 * START OF standard C library wrapping APIs
24397
 ******************************************************************************/
24398
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
24399
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
24400
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
24401
     defined(WOLFSSL_OPENSSH)))
24402
#ifndef NO_WOLFSSL_STUB
24403
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
24404
                                void *(*r) (void *, size_t, const char *,
24405
                                            int), void (*f) (void *))
24406
{
24407
    (void) m;
24408
    (void) r;
24409
    (void) f;
24410
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
24411
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
24412
24413
    return WOLFSSL_FAILURE;
24414
}
24415
#endif
24416
#endif
24417
24418
#if defined(OPENSSL_EXTRA)
24419
24420
/**
24421
 * free allocated memory resource
24422
 * @param str  a pointer to resource to be freed
24423
 * @param file dummy argument
24424
 * @param line dummy argument
24425
 */
24426
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
24427
{
24428
    (void)file;
24429
    (void)line;
24430
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
24431
}
24432
/**
24433
 * allocate memory with size of num
24434
 * @param num  size of memory allocation to be malloced
24435
 * @param file dummy argument
24436
 * @param line dummy argument
24437
 * @return a pointer to allocated memory on succssesful, otherwise NULL
24438
 */
24439
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
24440
{
24441
    (void)file;
24442
    (void)line;
24443
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
24444
}
24445
24446
#endif
24447
24448
/*******************************************************************************
24449
 * END OF standard C library wrapping APIs
24450
 ******************************************************************************/
24451
24452
/*******************************************************************************
24453
 * START OF EX_DATA APIs
24454
 ******************************************************************************/
24455
#ifdef HAVE_EX_DATA
24456
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
24457
{
24458
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
24459
}
24460
24461
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
24462
{
24463
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
24464
#ifdef MAX_EX_DATA
24465
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
24466
        return ex_data->ex_data[idx];
24467
    }
24468
#else
24469
    (void)ex_data;
24470
    (void)idx;
24471
#endif
24472
    return NULL;
24473
}
24474
24475
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
24476
    void *data)
24477
{
24478
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
24479
#ifdef MAX_EX_DATA
24480
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
24481
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
24482
        if (ex_data->ex_data_cleanup_routines[idx]) {
24483
            /* call cleanup then remove cleanup callback,
24484
             * since different value is being set */
24485
            if (ex_data->ex_data[idx])
24486
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
24487
            ex_data->ex_data_cleanup_routines[idx] = NULL;
24488
        }
24489
#endif
24490
        ex_data->ex_data[idx] = data;
24491
        return WOLFSSL_SUCCESS;
24492
    }
24493
#else
24494
    (void)ex_data;
24495
    (void)idx;
24496
    (void)data;
24497
#endif
24498
    return WOLFSSL_FAILURE;
24499
}
24500
24501
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
24502
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
24503
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
24504
    int idx,
24505
    void *data,
24506
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
24507
{
24508
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
24509
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
24510
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
24511
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
24512
        ex_data->ex_data[idx] = data;
24513
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
24514
        return WOLFSSL_SUCCESS;
24515
    }
24516
    return WOLFSSL_FAILURE;
24517
}
24518
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
24519
#endif /* HAVE_EX_DATA */
24520
24521
#ifdef HAVE_EX_DATA_CRYPTO
24522
/**
24523
 * Issues unique index for the class specified by class_index.
24524
 * Other parameter except class_index are ignored.
24525
 * Currently, following class_index are accepted:
24526
 *  - WOLF_CRYPTO_EX_INDEX_SSL
24527
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
24528
 *  - WOLF_CRYPTO_EX_INDEX_X509
24529
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
24530
 * @param argp  parameters to be saved
24531
 * @param argl  parameters to be saved
24532
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
24533
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
24534
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
24535
 * @return index value grater or equal to zero on success, -1 on failure.
24536
 */
24537
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
24538
                                           WOLFSSL_CRYPTO_EX_new* new_func,
24539
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
24540
                                           WOLFSSL_CRYPTO_EX_free* free_func)
24541
{
24542
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
24543
24544
    return wolfssl_get_ex_new_index(class_index, argl, argp, new_func,
24545
            dup_func, free_func);
24546
}
24547
#endif /* HAVE_EX_DATA_CRYPTO */
24548
24549
/*******************************************************************************
24550
 * END OF EX_DATA APIs
24551
 ******************************************************************************/
24552
24553
/*******************************************************************************
24554
 * START OF BUF_MEM API
24555
 ******************************************************************************/
24556
24557
#if defined(OPENSSL_EXTRA)
24558
24559
/* Begin functions for openssl/buffer.h */
24560
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
24561
{
24562
    WOLFSSL_BUF_MEM* buf;
24563
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
24564
                                                        DYNAMIC_TYPE_OPENSSL);
24565
    if (buf) {
24566
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
24567
    }
24568
    return buf;
24569
}
24570
24571
/* non-compat API returns length of buffer on success */
24572
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
24573
        char zeroFill)
24574
{
24575
24576
    int len_int = (int)len;
24577
    int mx;
24578
    char* tmp;
24579
24580
    /* verify provided arguments */
24581
    if (buf == NULL || len_int < 0) {
24582
        return 0; /* BAD_FUNC_ARG; */
24583
    }
24584
24585
    /* check to see if fits in existing length */
24586
    if (buf->length > len) {
24587
        buf->length = len;
24588
        return len_int;
24589
    }
24590
24591
    /* check to see if fits in max buffer */
24592
    if (buf->max >= len) {
24593
        if (buf->data != NULL && zeroFill) {
24594
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
24595
        }
24596
        buf->length = len;
24597
        return len_int;
24598
    }
24599
24600
    /* expand size, to handle growth */
24601
    mx = (len_int + 3) / 3 * 4;
24602
24603
#ifdef WOLFSSL_NO_REALLOC
24604
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
24605
    if (tmp != NULL && buf->data != NULL) {
24606
       XMEMCPY(tmp, buf->data, len_int);
24607
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
24608
       buf->data = NULL;
24609
    }
24610
#else
24611
    /* use realloc */
24612
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
24613
#endif
24614
24615
    if (tmp == NULL) {
24616
        return 0; /* ERR_R_MALLOC_FAILURE; */
24617
    }
24618
    buf->data = tmp;
24619
24620
    buf->max = (size_t)mx;
24621
    if (zeroFill)
24622
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
24623
    buf->length = len;
24624
24625
    return len_int;
24626
24627
}
24628
24629
/* returns length of buffer on success */
24630
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
24631
{
24632
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
24633
}
24634
24635
/* non-compat API returns length of buffer on success */
24636
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
24637
{
24638
    char* tmp;
24639
    int mx;
24640
24641
    /* verify provided arguments */
24642
    if (buf == NULL || len == 0 || (int)len <= 0) {
24643
        return 0; /* BAD_FUNC_ARG; */
24644
    }
24645
24646
    if (len == buf->length)
24647
        return (int)len;
24648
24649
    if (len > buf->length)
24650
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
24651
24652
    /* expand size, to handle growth */
24653
    mx = ((int)len + 3) / 3 * 4;
24654
24655
    /* We want to shrink the internal buffer */
24656
#ifdef WOLFSSL_NO_REALLOC
24657
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
24658
    if (tmp != NULL && buf->data != NULL)
24659
    {
24660
        XMEMCPY(tmp, buf->data, len);
24661
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
24662
        buf->data = NULL;
24663
    }
24664
#else
24665
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
24666
#endif
24667
24668
    if (tmp == NULL)
24669
        return 0;
24670
24671
    buf->data = tmp;
24672
    buf->length = len;
24673
    buf->max = (size_t)mx;
24674
24675
    return (int)len;
24676
}
24677
24678
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
24679
{
24680
    if (buf) {
24681
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
24682
        buf->data = NULL;
24683
        buf->max = 0;
24684
        buf->length = 0;
24685
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
24686
    }
24687
}
24688
/* End Functions for openssl/buffer.h */
24689
24690
#endif /* OPENSSL_EXTRA */
24691
24692
/*******************************************************************************
24693
 * END OF BUF_MEM API
24694
 ******************************************************************************/
24695
24696
#define WOLFSSL_CONF_INCLUDED
24697
#include <src/conf.c>
24698
24699
/*******************************************************************************
24700
 * START OF RAND API
24701
 ******************************************************************************/
24702
24703
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
24704
static int wolfSSL_RAND_InitMutex(void)
24705
{
24706
#ifndef WOLFSSL_MUTEX_INITIALIZER
24707
    if (gRandMethodsInit == 0) {
24708
        if (wc_InitMutex(&gRandMethodMutex) != 0) {
24709
            WOLFSSL_MSG("Bad Init Mutex rand methods");
24710
            return BAD_MUTEX_E;
24711
        }
24712
        gRandMethodsInit = 1;
24713
    }
24714
#endif
24715
    return 0;
24716
}
24717
#endif
24718
24719
#ifdef OPENSSL_EXTRA
24720
24721
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
24722
    ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST))
24723
/* In older FIPS bundles add check for reseed here since it does not exist in
24724
 * the older random.c certified files. */
24725
static pid_t currentRandPid = 0;
24726
#endif
24727
24728
/* Checks if the global RNG has been created. If not then one is created.
24729
 *
24730
 * Returns WOLFSSL_SUCCESS when no error is encountered.
24731
 */
24732
int wolfSSL_RAND_Init(void)
24733
{
24734
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
24735
#ifdef HAVE_GLOBAL_RNG
24736
    if (wc_LockMutex(&globalRNGMutex) == 0) {
24737
        if (initGlobalRNG == 0) {
24738
            ret = wc_InitRng(&globalRNG);
24739
            if (ret == 0) {
24740
            #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
24741
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
24742
                 defined(HAVE_SELFTEST))
24743
24744
                currentRandPid = getpid();
24745
            #endif
24746
                initGlobalRNG = 1;
24747
                ret = WOLFSSL_SUCCESS;
24748
            }
24749
        }
24750
        else {
24751
            /* GlobalRNG is already initialized */
24752
            ret = WOLFSSL_SUCCESS;
24753
        }
24754
24755
        wc_UnLockMutex(&globalRNGMutex);
24756
    }
24757
#endif
24758
    return ret;
24759
}
24760
24761
24762
/* WOLFSSL_SUCCESS on ok */
24763
int wolfSSL_RAND_seed(const void* seed, int len)
24764
{
24765
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
24766
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
24767
        if (gRandMethods && gRandMethods->seed) {
24768
            int ret = gRandMethods->seed(seed, len);
24769
            wc_UnLockMutex(&gRandMethodMutex);
24770
            return ret;
24771
        }
24772
        wc_UnLockMutex(&gRandMethodMutex);
24773
    }
24774
#else
24775
    (void)seed;
24776
    (void)len;
24777
#endif
24778
24779
    /* Make sure global shared RNG (globalRNG) is initialized */
24780
    return wolfSSL_RAND_Init();
24781
}
24782
24783
24784
/* Returns the path for reading seed data from.
24785
 * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
24786
 *
24787
 * Note uses stdlib by default unless XGETENV macro is overwritten
24788
 *
24789
 * fname buffer to hold path
24790
 * len   length of fname buffer
24791
 *
24792
 * Returns a pointer to fname on success and NULL on failure
24793
 */
24794
const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
24795
{
24796
#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV)
24797
    char* rt;
24798
24799
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
24800
24801
    if (fname == NULL) {
24802
        return NULL;
24803
    }
24804
24805
    XMEMSET(fname, 0, len);
24806
24807
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
24808
    if ((rt = XGETENV("RANDFILE")) != NULL) {
24809
        if (len > XSTRLEN(rt)) {
24810
            XMEMCPY(fname, rt, XSTRLEN(rt));
24811
        }
24812
        else {
24813
            WOLFSSL_MSG("RANDFILE too large for buffer");
24814
            rt = NULL;
24815
        }
24816
    }
24817
/* // NOLINTEND(concurrency-mt-unsafe) */
24818
24819
    /* $RANDFILE was not set or is too large, check $HOME */
24820
    if (rt == NULL) {
24821
        const char ap[] = "/.rnd";
24822
24823
        WOLFSSL_MSG("Environment variable RANDFILE not set");
24824
24825
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
24826
        if ((rt = XGETENV("HOME")) == NULL) {
24827
            #ifdef XALTHOMEVARNAME
24828
            if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) {
24829
                WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME
24830
                            " not set");
24831
                return NULL;
24832
            }
24833
            #else
24834
            WOLFSSL_MSG("Environment variable HOME not set");
24835
            return NULL;
24836
            #endif
24837
        }
24838
/* // NOLINTEND(concurrency-mt-unsafe) */
24839
24840
        if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
24841
            fname[0] = '\0';
24842
            XSTRNCAT(fname, rt, len);
24843
            XSTRNCAT(fname, ap, len - XSTRLEN(rt));
24844
            return fname;
24845
        }
24846
        else {
24847
            WOLFSSL_MSG("Path too large for buffer");
24848
            return NULL;
24849
        }
24850
    }
24851
24852
    return fname;
24853
#else
24854
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
24855
    WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, "
24856
                "not compiled in");
24857
    (void)fname;
24858
    (void)len;
24859
    return NULL;
24860
#endif
24861
}
24862
24863
24864
/* Writes 1024 bytes from the RNG to the given file name.
24865
 *
24866
 * fname name of file to write to
24867
 *
24868
 * Returns the number of bytes written
24869
 */
24870
int wolfSSL_RAND_write_file(const char* fname)
24871
{
24872
    int bytes = 0;
24873
24874
    WOLFSSL_ENTER("wolfSSL_RAND_write_file");
24875
24876
    if (fname == NULL) {
24877
        return WOLFSSL_FAILURE;
24878
    }
24879
24880
#ifndef NO_FILESYSTEM
24881
    {
24882
    #ifndef WOLFSSL_SMALL_STACK
24883
        unsigned char buf[1024];
24884
    #else
24885
        unsigned char* buf = (unsigned char *)XMALLOC(1024, NULL,
24886
                                                       DYNAMIC_TYPE_TMP_BUFFER);
24887
        if (buf == NULL) {
24888
            WOLFSSL_MSG("malloc failed");
24889
            return WOLFSSL_FAILURE;
24890
        }
24891
    #endif
24892
        bytes = 1024; /* default size of buf */
24893
24894
        if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
24895
            WOLFSSL_MSG("No RNG to use");
24896
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
24897
            return 0;
24898
        }
24899
24900
        if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) {
24901
            WOLFSSL_MSG("Error generating random buffer");
24902
            bytes = 0;
24903
        }
24904
        else {
24905
            XFILE f;
24906
24907
        #ifdef WOLFSSL_CHECK_MEM_ZERO
24908
            wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
24909
        #endif
24910
24911
            f = XFOPEN(fname, "wb");
24912
            if (f == XBADFILE) {
24913
                WOLFSSL_MSG("Error opening the file");
24914
                bytes = 0;
24915
            }
24916
            else {
24917
                size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f);
24918
                bytes = (int)bytes_written;
24919
                XFCLOSE(f);
24920
            }
24921
        }
24922
        ForceZero(buf, (word32)bytes);
24923
    #ifdef WOLFSSL_SMALL_STACK
24924
        XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
24925
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
24926
        wc_MemZero_Check(buf, sizeof(buf));
24927
    #endif
24928
    }
24929
#endif
24930
24931
    return bytes;
24932
}
24933
24934
#ifndef FREERTOS_TCP
24935
24936
/* These constant values are protocol values made by egd */
24937
#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \
24938
    !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \
24939
    defined(HAVE_SYS_UN_H)
24940
    #define WOLFSSL_EGD_NBLOCK 0x01
24941
    #include <sys/un.h>
24942
#endif
24943
24944
/* This collects entropy from the path nm and seeds the global PRNG with it.
24945
 *
24946
 * nm is the file path to the egd server
24947
 *
24948
 * Returns the number of bytes read.
24949
 */
24950
int wolfSSL_RAND_egd(const char* nm)
24951
{
24952
#ifdef WOLFSSL_EGD_NBLOCK
24953
    struct sockaddr_un rem;
24954
    int fd;
24955
    int ret = WOLFSSL_SUCCESS;
24956
    word32 bytes = 0;
24957
    word32 idx   = 0;
24958
#ifndef WOLFSSL_SMALL_STACK
24959
    unsigned char buf[256];
24960
#else
24961
    unsigned char* buf;
24962
    buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
24963
    if (buf == NULL) {
24964
        WOLFSSL_MSG("Not enough memory");
24965
        return WOLFSSL_FATAL_ERROR;
24966
    }
24967
#endif
24968
24969
    XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
24970
    if (nm == NULL) {
24971
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
24972
        return WOLFSSL_FATAL_ERROR;
24973
    }
24974
24975
    fd = socket(AF_UNIX, SOCK_STREAM, 0);
24976
    if (fd < 0) {
24977
        WOLFSSL_MSG("Error creating socket");
24978
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
24979
        return WOLFSSL_FATAL_ERROR;
24980
    }
24981
    rem.sun_family = AF_UNIX;
24982
    XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
24983
    rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
24984
24985
    /* connect to egd server */
24986
    if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
24987
        WOLFSSL_MSG("error connecting to egd server");
24988
        ret = WOLFSSL_FATAL_ERROR;
24989
    }
24990
24991
#ifdef WOLFSSL_CHECK_MEM_ZERO
24992
    if (ret == WOLFSSL_SUCCESS) {
24993
        wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
24994
    }
24995
#endif
24996
    while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
24997
        buf[idx]     = WOLFSSL_EGD_NBLOCK;
24998
        buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
24999
        ret = (int)write(fd, buf + idx, 2);
25000
        if (ret != 2) {
25001
            if (errno == EAGAIN) {
25002
                ret = WOLFSSL_SUCCESS;
25003
                continue;
25004
            }
25005
            WOLFSSL_MSG("error requesting entropy from egd server");
25006
            ret = WOLFSSL_FATAL_ERROR;
25007
            break;
25008
        }
25009
25010
        /* attempting to read */
25011
        buf[idx] = 0;
25012
        ret = (int)read(fd, buf + idx, 256 - bytes);
25013
        if (ret == 0) {
25014
            WOLFSSL_MSG("error reading entropy from egd server");
25015
            ret = WOLFSSL_FATAL_ERROR;
25016
            break;
25017
        }
25018
        if (ret > 0 && buf[idx] > 0) {
25019
            bytes += buf[idx]; /* egd stores amount sent in first byte */
25020
            if (bytes + idx > 255 || buf[idx] > ret) {
25021
                WOLFSSL_MSG("Buffer error");
25022
                ret = WOLFSSL_FATAL_ERROR;
25023
                break;
25024
            }
25025
            XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
25026
            idx = bytes;
25027
            ret = WOLFSSL_SUCCESS;
25028
            if (bytes >= 255) {
25029
                break;
25030
            }
25031
        }
25032
        else {
25033
            if (errno == EAGAIN || errno == EINTR) {
25034
                WOLFSSL_MSG("EGD would read");
25035
                ret = WOLFSSL_SUCCESS; /* try again */
25036
            }
25037
            else if (buf[idx] == 0) {
25038
                /* if egd returned 0 then there is no more entropy to be had.
25039
                   Do not try more reads. */
25040
                ret = WOLFSSL_SUCCESS;
25041
                break;
25042
            }
25043
            else {
25044
                WOLFSSL_MSG("Error with read");
25045
                ret = WOLFSSL_FATAL_ERROR;
25046
            }
25047
        }
25048
    }
25049
25050
    if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
25051
        /* call to check global RNG is created */
25052
        if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
25053
            WOLFSSL_MSG("Error with initializing global RNG structure");
25054
            ret = WOLFSSL_FATAL_ERROR;
25055
        }
25056
        else if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
25057
                != 0) {
25058
            WOLFSSL_MSG("Error with reseeding DRBG structure");
25059
            ret = WOLFSSL_FATAL_ERROR;
25060
        }
25061
        #ifdef SHOW_SECRETS
25062
        else { /* print out entropy found only when no error occurred */
25063
            word32 i;
25064
            printf("EGD Entropy = ");
25065
            for (i = 0; i < bytes; i++) {
25066
                printf("%02X", buf[i]);
25067
            }
25068
            printf("\n");
25069
        }
25070
        #endif
25071
    }
25072
25073
    ForceZero(buf, bytes);
25074
#ifdef WOLFSSL_SMALL_STACK
25075
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
25076
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
25077
    wc_MemZero_Check(buf, 256);
25078
#endif
25079
    close(fd);
25080
25081
    if (ret == WOLFSSL_SUCCESS) {
25082
        return (int)bytes;
25083
    }
25084
    else {
25085
        return ret;
25086
    }
25087
#else
25088
    WOLFSSL_MSG("Type of socket needed is not available");
25089
    WOLFSSL_MSG("\tor using mode where DRBG API is not available");
25090
    (void)nm;
25091
25092
    return WOLFSSL_FATAL_ERROR;
25093
#endif /* WOLFSSL_EGD_NBLOCK */
25094
}
25095
25096
#endif /* !FREERTOS_TCP */
25097
25098
void wolfSSL_RAND_Cleanup(void)
25099
{
25100
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25101
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
25102
        if (gRandMethods && gRandMethods->cleanup)
25103
            gRandMethods->cleanup();
25104
        wc_UnLockMutex(&gRandMethodMutex);
25105
    }
25106
25107
    #ifndef WOLFSSL_MUTEX_INITIALIZER
25108
    if (wc_FreeMutex(&gRandMethodMutex) == 0)
25109
        gRandMethodsInit = 0;
25110
    #endif
25111
#endif
25112
#ifdef HAVE_GLOBAL_RNG
25113
    if (wc_LockMutex(&globalRNGMutex) == 0) {
25114
        if (initGlobalRNG) {
25115
            wc_FreeRng(&globalRNG);
25116
            initGlobalRNG = 0;
25117
        }
25118
        wc_UnLockMutex(&globalRNGMutex);
25119
    }
25120
#endif
25121
}
25122
25123
/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise
25124
 * WOLFSSL_FAILURE */
25125
int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
25126
{
25127
    int ret;
25128
    int hash;
25129
    byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */
25130
25131
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25132
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
25133
        if (gRandMethods && gRandMethods->pseudorand) {
25134
            ret = gRandMethods->pseudorand(buf, num);
25135
            wc_UnLockMutex(&gRandMethodMutex);
25136
            return ret;
25137
        }
25138
        wc_UnLockMutex(&gRandMethodMutex);
25139
    }
25140
#endif
25141
25142
#ifdef WOLFSSL_HAVE_PRF
25143
    #ifndef NO_SHA256
25144
    hash = WC_SHA256;
25145
    #elif defined(WOLFSSL_SHA384)
25146
    hash = WC_SHA384;
25147
    #elif !defined(NO_SHA)
25148
    hash = WC_SHA;
25149
    #elif !defined(NO_MD5)
25150
    hash = WC_MD5;
25151
    #endif
25152
25153
    /* get secret value from source of entropy */
25154
    ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
25155
25156
    /* uses input buffer to seed for pseudo random number generation, each
25157
     * thread will potentially have different results this way */
25158
    if (ret == WOLFSSL_SUCCESS) {
25159
        PRIVATE_KEY_UNLOCK();
25160
        ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
25161
                hash, NULL, INVALID_DEVID);
25162
        PRIVATE_KEY_LOCK();
25163
        ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
25164
    }
25165
#else
25166
    /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
25167
    ret = wolfSSL_RAND_bytes(buf, num);
25168
    (void)hash;
25169
    (void)secret;
25170
#endif
25171
    return ret;
25172
}
25173
25174
/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0
25175
 * on failure */
25176
int wolfSSL_RAND_bytes(unsigned char* buf, int num)
25177
{
25178
    int     ret = 0;
25179
    WC_RNG* rng = NULL;
25180
    WC_DECLARE_VAR(tmpRNG, WC_RNG, 1, 0);
25181
    int initTmpRng = 0;
25182
#ifdef HAVE_GLOBAL_RNG
25183
    int used_global = 0;
25184
#endif
25185
25186
    WOLFSSL_ENTER("wolfSSL_RAND_bytes");
25187
    /* sanity check */
25188
    if (buf == NULL || num < 0)
25189
        /* return code compliant with OpenSSL */
25190
        return 0;
25191
25192
    /* if a RAND callback has been set try and use it */
25193
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25194
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
25195
        if (gRandMethods && gRandMethods->bytes) {
25196
            ret = gRandMethods->bytes(buf, num);
25197
            wc_UnLockMutex(&gRandMethodMutex);
25198
            return ret;
25199
        }
25200
        wc_UnLockMutex(&gRandMethodMutex);
25201
    }
25202
#endif
25203
#ifdef HAVE_GLOBAL_RNG
25204
    if (initGlobalRNG) {
25205
        if (wc_LockMutex(&globalRNGMutex) != 0) {
25206
            WOLFSSL_MSG("Bad Lock Mutex rng");
25207
            return ret;
25208
        }
25209
        /* the above access to initGlobalRNG is racey -- recheck it now that we
25210
         * have the lock.
25211
         */
25212
        if (initGlobalRNG) {
25213
        #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
25214
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
25215
                 defined(HAVE_SELFTEST))
25216
            pid_t p;
25217
25218
            p = getpid();
25219
            if (p != currentRandPid) {
25220
                wc_UnLockMutex(&globalRNGMutex);
25221
                if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) {
25222
                    WOLFSSL_MSG("Issue with check pid and reseed");
25223
                    ret = WOLFSSL_FAILURE;
25224
                }
25225
25226
                /* reclaim lock after wolfSSL_RAND_poll */
25227
                if (wc_LockMutex(&globalRNGMutex) != 0) {
25228
                    WOLFSSL_MSG("Bad Lock Mutex rng");
25229
                    return ret;
25230
                }
25231
                currentRandPid = p;
25232
            }
25233
        #endif
25234
            rng = &globalRNG;
25235
            used_global = 1;
25236
        }
25237
        else {
25238
            wc_UnLockMutex(&globalRNGMutex);
25239
        }
25240
    }
25241
25242
    if (used_global == 0)
25243
#endif
25244
    {
25245
        WC_ALLOC_VAR_EX(tmpRNG, WC_RNG, 1, NULL, DYNAMIC_TYPE_RNG,
25246
            return ret);
25247
        if (wc_InitRng(tmpRNG) == 0) {
25248
            rng = tmpRNG;
25249
            initTmpRng = 1;
25250
        }
25251
    }
25252
    if (rng) {
25253
        /* handles size greater than RNG_MAX_BLOCK_LEN */
25254
        int blockCount = num / RNG_MAX_BLOCK_LEN;
25255
25256
        while (blockCount--) {
25257
            ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
25258
            if (ret != 0) {
25259
                WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
25260
                break;
25261
            }
25262
            num -= RNG_MAX_BLOCK_LEN;
25263
            buf += RNG_MAX_BLOCK_LEN;
25264
        }
25265
25266
        if (ret == 0 && num)
25267
            ret = wc_RNG_GenerateBlock(rng, buf, (word32)num);
25268
25269
        if (ret != 0)
25270
            WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
25271
        else
25272
            ret = WOLFSSL_SUCCESS;
25273
    }
25274
25275
#ifdef HAVE_GLOBAL_RNG
25276
    if (used_global == 1)
25277
        wc_UnLockMutex(&globalRNGMutex);
25278
#endif
25279
    if (initTmpRng)
25280
        wc_FreeRng(tmpRNG);
25281
    WC_FREE_VAR_EX(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
25282
25283
    return ret;
25284
}
25285
25286
25287
int wolfSSL_RAND_poll(void)
25288
{
25289
    byte  entropy[16];
25290
    int  ret = 0;
25291
    word32 entropy_sz = 16;
25292
25293
    WOLFSSL_ENTER("wolfSSL_RAND_poll");
25294
    if (initGlobalRNG == 0){
25295
        WOLFSSL_MSG("Global RNG no Init");
25296
        return  WOLFSSL_FAILURE;
25297
    }
25298
    ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
25299
    if (ret != 0) {
25300
        WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
25301
        ret = WOLFSSL_FAILURE;
25302
    }
25303
    else {
25304
#ifdef HAVE_HASHDRBG
25305
        if (wc_LockMutex(&globalRNGMutex) != 0) {
25306
            WOLFSSL_MSG("Bad Lock Mutex rng");
25307
            return ret;
25308
        }
25309
25310
        ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
25311
        if (ret != 0) {
25312
            WOLFSSL_MSG("Error reseeding DRBG");
25313
            ret = WOLFSSL_FAILURE;
25314
        }
25315
        else {
25316
            ret = WOLFSSL_SUCCESS;
25317
        }
25318
        wc_UnLockMutex(&globalRNGMutex);
25319
#elif defined(HAVE_INTEL_RDRAND)
25320
        WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without "
25321
                    "HAVE_HASHDRBG");
25322
        ret = WOLFSSL_SUCCESS;
25323
#else
25324
        WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set");
25325
        ret = WOLFSSL_FAILURE;
25326
#endif
25327
    }
25328
25329
    return ret;
25330
}
25331
25332
    /* If a valid struct is provided with function pointers, will override
25333
       RAND_seed, bytes, cleanup, add, pseudo_bytes and status.  If a NULL
25334
       pointer is passed in, it will cancel any previous function overrides.
25335
25336
       Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
25337
    int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
25338
    {
25339
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25340
        if (wolfSSL_RAND_InitMutex() == 0 &&
25341
                wc_LockMutex(&gRandMethodMutex) == 0) {
25342
            gRandMethods = methods;
25343
            wc_UnLockMutex(&gRandMethodMutex);
25344
            return WOLFSSL_SUCCESS;
25345
        }
25346
    #else
25347
        (void)methods;
25348
    #endif
25349
        return WOLFSSL_FAILURE;
25350
    }
25351
25352
    /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
25353
    int wolfSSL_RAND_status(void)
25354
    {
25355
        int ret = WOLFSSL_SUCCESS;
25356
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25357
        if (wolfSSL_RAND_InitMutex() == 0 &&
25358
                wc_LockMutex(&gRandMethodMutex) == 0) {
25359
            if (gRandMethods && gRandMethods->status)
25360
                ret = gRandMethods->status();
25361
            wc_UnLockMutex(&gRandMethodMutex);
25362
        }
25363
        else {
25364
            ret = WOLFSSL_FAILURE;
25365
        }
25366
    #else
25367
        /* wolfCrypt provides enough seed internally, so return success */
25368
    #endif
25369
        return ret;
25370
    }
25371
25372
    void wolfSSL_RAND_add(const void* add, int len, double entropy)
25373
    {
25374
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
25375
        if (wolfSSL_RAND_InitMutex() == 0 &&
25376
                wc_LockMutex(&gRandMethodMutex) == 0) {
25377
            if (gRandMethods && gRandMethods->add) {
25378
                /* callback has return code, but RAND_add does not */
25379
                (void)gRandMethods->add(add, len, entropy);
25380
            }
25381
            wc_UnLockMutex(&gRandMethodMutex);
25382
        }
25383
    #else
25384
        /* wolfSSL seeds/adds internally, use explicit RNG if you want
25385
           to take control */
25386
        (void)add;
25387
        (void)len;
25388
        (void)entropy;
25389
    #endif
25390
    }
25391
25392
25393
#ifndef NO_WOLFSSL_STUB
25394
void wolfSSL_RAND_screen(void)
25395
{
25396
    WOLFSSL_STUB("RAND_screen");
25397
}
25398
#endif
25399
25400
int wolfSSL_RAND_load_file(const char* fname, long len)
25401
{
25402
    (void)fname;
25403
    /* wolfCrypt provides enough entropy internally or will report error */
25404
    if (len == -1)
25405
        return 1024;
25406
    else
25407
        return (int)len;
25408
}
25409
25410
#endif /* OPENSSL_EXTRA */
25411
25412
/*******************************************************************************
25413
 * END OF RAND API
25414
 ******************************************************************************/
25415
25416
/*******************************************************************************
25417
 * START OF EVP_CIPHER API
25418
 ******************************************************************************/
25419
25420
#ifdef OPENSSL_EXTRA
25421
25422
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
25423
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
25424
    {
25425
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
25426
25427
        if (ctx == NULL) {
25428
            WOLFSSL_MSG("Bad function argument");
25429
            return WOLFSSL_FATAL_ERROR;
25430
        }
25431
25432
        switch (ctx->cipherType) {
25433
#ifndef NO_AES
25434
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
25435
            case WC_AES_128_CBC_TYPE :
25436
            case WC_AES_192_CBC_TYPE :
25437
            case WC_AES_256_CBC_TYPE :
25438
                WOLFSSL_MSG("AES CBC");
25439
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
25440
                break;
25441
#endif
25442
#ifdef HAVE_AESGCM
25443
            case WC_AES_128_GCM_TYPE :
25444
            case WC_AES_192_GCM_TYPE :
25445
            case WC_AES_256_GCM_TYPE :
25446
                WOLFSSL_MSG("AES GCM");
25447
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
25448
                break;
25449
#endif /* HAVE_AESGCM */
25450
#ifdef HAVE_AESCCM
25451
            case WC_AES_128_CCM_TYPE :
25452
            case WC_AES_192_CCM_TYPE :
25453
            case WC_AES_256_CCM_TYPE :
25454
                WOLFSSL_MSG("AES CCM");
25455
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
25456
                break;
25457
#endif /* HAVE_AESCCM */
25458
#ifdef HAVE_AES_ECB
25459
            case WC_AES_128_ECB_TYPE :
25460
            case WC_AES_192_ECB_TYPE :
25461
            case WC_AES_256_ECB_TYPE :
25462
                WOLFSSL_MSG("AES ECB");
25463
                break;
25464
#endif
25465
#ifdef WOLFSSL_AES_COUNTER
25466
            case WC_AES_128_CTR_TYPE :
25467
            case WC_AES_192_CTR_TYPE :
25468
            case WC_AES_256_CTR_TYPE :
25469
                WOLFSSL_MSG("AES CTR");
25470
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
25471
                break;
25472
#endif /* WOLFSSL_AES_COUNTER */
25473
#ifdef WOLFSSL_AES_CFB
25474
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
25475
            case WC_AES_128_CFB1_TYPE:
25476
            case WC_AES_192_CFB1_TYPE:
25477
            case WC_AES_256_CFB1_TYPE:
25478
                WOLFSSL_MSG("AES CFB1");
25479
                break;
25480
            case WC_AES_128_CFB8_TYPE:
25481
            case WC_AES_192_CFB8_TYPE:
25482
            case WC_AES_256_CFB8_TYPE:
25483
                WOLFSSL_MSG("AES CFB8");
25484
                break;
25485
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
25486
            case WC_AES_128_CFB128_TYPE:
25487
            case WC_AES_192_CFB128_TYPE:
25488
            case WC_AES_256_CFB128_TYPE:
25489
                WOLFSSL_MSG("AES CFB128");
25490
                break;
25491
#endif /* WOLFSSL_AES_CFB */
25492
#if defined(WOLFSSL_AES_OFB)
25493
            case WC_AES_128_OFB_TYPE:
25494
            case WC_AES_192_OFB_TYPE:
25495
            case WC_AES_256_OFB_TYPE:
25496
                WOLFSSL_MSG("AES OFB");
25497
                break;
25498
#endif /* WOLFSSL_AES_OFB */
25499
#ifdef WOLFSSL_AES_XTS
25500
            case WC_AES_128_XTS_TYPE:
25501
            case WC_AES_256_XTS_TYPE:
25502
                WOLFSSL_MSG("AES XTS");
25503
                break;
25504
#endif /* WOLFSSL_AES_XTS */
25505
#endif /* NO_AES */
25506
25507
#ifdef HAVE_ARIA
25508
            case WC_ARIA_128_GCM_TYPE :
25509
            case WC_ARIA_192_GCM_TYPE :
25510
            case WC_ARIA_256_GCM_TYPE :
25511
                WOLFSSL_MSG("ARIA GCM");
25512
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
25513
                break;
25514
#endif /* HAVE_ARIA */
25515
25516
#ifndef NO_DES3
25517
            case WC_DES_CBC_TYPE :
25518
                WOLFSSL_MSG("DES CBC");
25519
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
25520
                break;
25521
25522
            case WC_DES_EDE3_CBC_TYPE :
25523
                WOLFSSL_MSG("DES EDE3 CBC");
25524
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
25525
                break;
25526
#endif
25527
#ifdef WOLFSSL_DES_ECB
25528
            case WC_DES_ECB_TYPE :
25529
                WOLFSSL_MSG("DES ECB");
25530
                break;
25531
            case WC_DES_EDE3_ECB_TYPE :
25532
                WOLFSSL_MSG("DES3 ECB");
25533
                break;
25534
#endif
25535
            case WC_ARC4_TYPE :
25536
                WOLFSSL_MSG("ARC4");
25537
                break;
25538
25539
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
25540
            case WC_CHACHA20_POLY1305_TYPE:
25541
                break;
25542
#endif
25543
25544
#ifdef HAVE_CHACHA
25545
            case WC_CHACHA20_TYPE:
25546
                break;
25547
#endif
25548
25549
#ifdef WOLFSSL_SM4_ECB
25550
            case WC_SM4_ECB_TYPE:
25551
                break;
25552
#endif
25553
#ifdef WOLFSSL_SM4_CBC
25554
            case WC_SM4_CBC_TYPE:
25555
                WOLFSSL_MSG("SM4 CBC");
25556
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
25557
                break;
25558
#endif
25559
#ifdef WOLFSSL_SM4_CTR
25560
            case WC_SM4_CTR_TYPE:
25561
                WOLFSSL_MSG("SM4 CTR");
25562
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
25563
                break;
25564
#endif
25565
#ifdef WOLFSSL_SM4_GCM
25566
            case WC_SM4_GCM_TYPE:
25567
                WOLFSSL_MSG("SM4 GCM");
25568
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
25569
                break;
25570
#endif
25571
#ifdef WOLFSSL_SM4_CCM
25572
            case WC_SM4_CCM_TYPE:
25573
                WOLFSSL_MSG("SM4 CCM");
25574
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
25575
                break;
25576
#endif
25577
25578
            case WC_NULL_CIPHER_TYPE :
25579
                WOLFSSL_MSG("NULL");
25580
                break;
25581
25582
            default: {
25583
                WOLFSSL_MSG("bad type");
25584
                return WOLFSSL_FATAL_ERROR;
25585
            }
25586
        }
25587
        return WOLFSSL_SUCCESS;
25588
    }
25589
25590
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
25591
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
25592
    {
25593
25594
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
25595
25596
        if (ctx == NULL) {
25597
            WOLFSSL_MSG("Bad function argument");
25598
            return WOLFSSL_FATAL_ERROR;
25599
        }
25600
25601
        switch (ctx->cipherType) {
25602
25603
#ifndef NO_AES
25604
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
25605
            case WC_AES_128_CBC_TYPE :
25606
            case WC_AES_192_CBC_TYPE :
25607
            case WC_AES_256_CBC_TYPE :
25608
                WOLFSSL_MSG("AES CBC");
25609
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
25610
                break;
25611
#endif
25612
#ifdef HAVE_AESGCM
25613
            case WC_AES_128_GCM_TYPE :
25614
            case WC_AES_192_GCM_TYPE :
25615
            case WC_AES_256_GCM_TYPE :
25616
                WOLFSSL_MSG("AES GCM");
25617
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
25618
                break;
25619
#endif
25620
#ifdef HAVE_AES_ECB
25621
            case WC_AES_128_ECB_TYPE :
25622
            case WC_AES_192_ECB_TYPE :
25623
            case WC_AES_256_ECB_TYPE :
25624
                WOLFSSL_MSG("AES ECB");
25625
                break;
25626
#endif
25627
#ifdef WOLFSSL_AES_COUNTER
25628
            case WC_AES_128_CTR_TYPE :
25629
            case WC_AES_192_CTR_TYPE :
25630
            case WC_AES_256_CTR_TYPE :
25631
                WOLFSSL_MSG("AES CTR");
25632
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
25633
                break;
25634
#endif
25635
25636
#endif /* NO_AES */
25637
25638
#ifdef HAVE_ARIA
25639
            case WC_ARIA_128_GCM_TYPE :
25640
            case WC_ARIA_192_GCM_TYPE :
25641
            case WC_ARIA_256_GCM_TYPE :
25642
                WOLFSSL_MSG("ARIA GCM");
25643
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
25644
                break;
25645
#endif /* HAVE_ARIA */
25646
25647
#ifndef NO_DES3
25648
            case WC_DES_CBC_TYPE :
25649
                WOLFSSL_MSG("DES CBC");
25650
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
25651
                break;
25652
25653
            case WC_DES_EDE3_CBC_TYPE :
25654
                WOLFSSL_MSG("DES EDE3 CBC");
25655
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
25656
                break;
25657
#endif
25658
#ifdef WOLFSSL_DES_ECB
25659
            case WC_DES_ECB_TYPE :
25660
                WOLFSSL_MSG("DES ECB");
25661
                break;
25662
            case WC_DES_EDE3_ECB_TYPE :
25663
                WOLFSSL_MSG("DES3 ECB");
25664
                break;
25665
#endif
25666
25667
            case WC_ARC4_TYPE :
25668
                WOLFSSL_MSG("ARC4");
25669
                break;
25670
25671
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
25672
            case WC_CHACHA20_POLY1305_TYPE:
25673
                break;
25674
#endif
25675
25676
#ifdef HAVE_CHACHA
25677
            case WC_CHACHA20_TYPE:
25678
                break;
25679
#endif
25680
25681
#ifdef WOLFSSL_SM4_ECB
25682
            case WC_SM4_ECB_TYPE:
25683
                break;
25684
#endif
25685
#ifdef WOLFSSL_SM4_CBC
25686
            case WC_SM4_CBC_TYPE:
25687
                WOLFSSL_MSG("SM4 CBC");
25688
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
25689
                break;
25690
#endif
25691
#ifdef WOLFSSL_SM4_CTR
25692
            case WC_SM4_CTR_TYPE:
25693
                WOLFSSL_MSG("SM4 CTR");
25694
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
25695
                break;
25696
#endif
25697
#ifdef WOLFSSL_SM4_GCM
25698
            case WC_SM4_GCM_TYPE:
25699
                WOLFSSL_MSG("SM4 GCM");
25700
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
25701
                break;
25702
#endif
25703
#ifdef WOLFSSL_SM4_CCM
25704
            case WC_SM4_CCM_TYPE:
25705
                WOLFSSL_MSG("SM4 CCM");
25706
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
25707
                break;
25708
#endif
25709
25710
            case WC_NULL_CIPHER_TYPE :
25711
                WOLFSSL_MSG("NULL");
25712
                break;
25713
25714
            default: {
25715
                WOLFSSL_MSG("bad type");
25716
                return WOLFSSL_FATAL_ERROR;
25717
            }
25718
        }
25719
        return WOLFSSL_SUCCESS;
25720
    }
25721
25722
#ifndef NO_DES3
25723
25724
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
25725
                            unsigned char* iv, int len)
25726
{
25727
    (void)len;
25728
25729
    WOLFSSL_MSG("wolfSSL_3des_iv");
25730
25731
    if (ctx == NULL || iv == NULL) {
25732
        WOLFSSL_MSG("Bad function argument");
25733
        return;
25734
    }
25735
25736
    if (doset)
25737
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
25738
    else
25739
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
25740
}
25741
25742
#endif /* NO_DES3 */
25743
25744
25745
#ifndef NO_AES
25746
25747
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
25748
                      unsigned char* iv, int len)
25749
{
25750
    (void)len;
25751
25752
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
25753
25754
    if (ctx == NULL || iv == NULL) {
25755
        WOLFSSL_MSG("Bad function argument");
25756
        return;
25757
    }
25758
25759
    if (doset)
25760
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
25761
    else
25762
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
25763
}
25764
25765
#endif /* NO_AES */
25766
25767
#endif /* OPENSSL_EXTRA */
25768
25769
/*******************************************************************************
25770
 * END OF EVP_CIPHER API
25771
 ******************************************************************************/
25772
25773
#ifndef NO_CERTS
25774
25775
#define WOLFSSL_X509_STORE_INCLUDED
25776
#include <src/x509_str.c>
25777
25778
#define WOLFSSL_SSL_P7P12_INCLUDED
25779
#include <src/ssl_p7p12.c>
25780
25781
#endif /* !NO_CERTS */
25782
25783
25784
/*******************************************************************************
25785
 * BEGIN OPENSSL FIPS DRBG APIs
25786
 ******************************************************************************/
25787
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
25788
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
25789
{
25790
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25791
    if (ctx != NULL) {
25792
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
25793
        ctx->type = type;
25794
        ctx->xflags = (int)flags;
25795
        ctx->status = DRBG_STATUS_UNINITIALISED;
25796
        ret = WOLFSSL_SUCCESS;
25797
    }
25798
    return ret;
25799
}
25800
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
25801
{
25802
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25803
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
25804
        NULL, DYNAMIC_TYPE_OPENSSL);
25805
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
25806
    if (ret == WOLFSSL_SUCCESS && type != 0) {
25807
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
25808
    }
25809
    if (ret != WOLFSSL_SUCCESS) {
25810
        WOLFSSL_ERROR(ret);
25811
        wolfSSL_FIPS_drbg_free(ctx);
25812
        ctx = NULL;
25813
    }
25814
    return ctx;
25815
}
25816
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
25817
    const unsigned char* pers, size_t perslen)
25818
{
25819
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25820
    if (ctx != NULL && ctx->rng == NULL) {
25821
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
25822
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
25823
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
25824
    #else
25825
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
25826
        if (ctx->rng != NULL) {
25827
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
25828
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
25829
        #else
25830
            ret = wc_InitRng(ctx->rng);
25831
            (void)pers;
25832
            (void)perslen;
25833
        #endif
25834
            if (ret != 0) {
25835
                WOLFSSL_ERROR(ret);
25836
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
25837
                ctx->rng = NULL;
25838
            }
25839
        }
25840
    #endif
25841
    }
25842
    if (ctx != NULL && ctx->rng != NULL) {
25843
        ctx->status = DRBG_STATUS_READY;
25844
        ret = WOLFSSL_SUCCESS;
25845
    }
25846
    return ret;
25847
}
25848
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
25849
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
25850
    size_t entropy_blocklen,
25851
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
25852
{
25853
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25854
    if (ctx != NULL) {
25855
        ctx->entropy_get = entropy_get;
25856
        ctx->entropy_clean = entropy_clean;
25857
        ctx->entropy_blocklen = entropy_blocklen;
25858
        ctx->none_get = none_get;
25859
        ctx->nonce_clean = nonce_clean;
25860
        ret = WOLFSSL_SUCCESS;
25861
    }
25862
    return ret;
25863
}
25864
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
25865
{
25866
    /* not implemented */
25867
    (void)buf;
25868
    (void)num;
25869
    (void)entropy;
25870
}
25871
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
25872
    size_t adinlen)
25873
{
25874
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25875
    if (ctx != NULL && ctx->rng != NULL) {
25876
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
25877
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
25878
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
25879
            ret = WOLFSSL_SUCCESS;
25880
        }
25881
    #else
25882
        ret = WOLFSSL_SUCCESS;
25883
        (void)adin;
25884
        (void)adinlen;
25885
    #endif
25886
    }
25887
    return ret;
25888
}
25889
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
25890
    size_t outlen, int prediction_resistance, const unsigned char* adin,
25891
    size_t adinlen)
25892
{
25893
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
25894
    if (ctx != NULL && ctx->rng != NULL) {
25895
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
25896
        if (ret == 0) {
25897
            ret = WOLFSSL_SUCCESS;
25898
        }
25899
    }
25900
    (void)prediction_resistance;
25901
    (void)adin;
25902
    (void)adinlen;
25903
    return ret;
25904
}
25905
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
25906
{
25907
    if (ctx != NULL && ctx->rng != NULL) {
25908
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
25909
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
25910
        wc_rng_free(ctx->rng);
25911
    #else
25912
        wc_FreeRng(ctx->rng);
25913
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
25914
    #endif
25915
        ctx->rng = NULL;
25916
        ctx->status = DRBG_STATUS_UNINITIALISED;
25917
    }
25918
    return WOLFSSL_SUCCESS;
25919
}
25920
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
25921
{
25922
    if (ctx != NULL) {
25923
        /* As safety check if free'ing the default drbg, then mark global NULL.
25924
         * Technically the user should not call free on the default drbg. */
25925
        if (ctx == gDrbgDefCtx) {
25926
            gDrbgDefCtx = NULL;
25927
        }
25928
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
25929
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
25930
    }
25931
}
25932
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
25933
{
25934
    if (gDrbgDefCtx == NULL) {
25935
        gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
25936
    }
25937
    return gDrbgDefCtx;
25938
}
25939
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
25940
{
25941
    /* not implemented */
25942
    (void)buf;
25943
    (void)pctr;
25944
}
25945
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
25946
{
25947
    if (ctx != NULL) {
25948
        return ctx->app_data;
25949
    }
25950
    return NULL;
25951
}
25952
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
25953
{
25954
    if (ctx != NULL) {
25955
        ctx->app_data = app_data;
25956
    }
25957
}
25958
#endif
25959
/*******************************************************************************
25960
 * END OF OPENSSL FIPS DRBG APIs
25961
 ******************************************************************************/
25962
25963
25964
#endif /* !WOLFCRYPT_ONLY */