Coverage Report

Created: 2023-02-22 06:39

/src/wolfssl/src/ssl.c
Line
Count
Source (jump to first uncovered line)
1
/* ssl.c
2
 *
3
 * Copyright (C) 2006-2022 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 2 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
23
#ifdef HAVE_CONFIG_H
24
    #include <config.h>
25
#endif
26
27
#include <wolfssl/wolfcrypt/settings.h>
28
#if defined(OPENSSL_EXTRA) && !defined(_WIN32)
29
    /* turn on GNU extensions for XISASCII */
30
    #undef  _GNU_SOURCE
31
    #define _GNU_SOURCE
32
#endif
33
34
#if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \
35
    defined(OPENSSL_EXTRA_X509_SMALL)
36
37
#include <wolfssl/internal.h>
38
#include <wolfssl/error-ssl.h>
39
#include <wolfssl/wolfcrypt/coding.h>
40
#include <wolfssl/wolfcrypt/kdf.h>
41
#ifdef NO_INLINE
42
    #include <wolfssl/wolfcrypt/misc.h>
43
#else
44
    #define WOLFSSL_MISC_INCLUDED
45
    #include <wolfcrypt/src/misc.c>
46
#endif
47
48
#ifdef HAVE_ERRNO_H
49
    #include <errno.h>
50
#endif
51
52
53
#if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
54
    #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
55
                && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
56
                && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
57
        #error "No cipher suites defined because DH disabled, ECC disabled, and no static suites defined. Please see top of README"
58
    #endif
59
    #ifdef WOLFSSL_CERT_GEN
60
        /* need access to Cert struct for creating certificate */
61
        #include <wolfssl/wolfcrypt/asn_public.h>
62
    #endif
63
#endif
64
65
#if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA)     \
66
    || defined(OPENSSL_EXTRA_X509_SMALL)                    \
67
    || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
68
    #include <wolfssl/openssl/evp.h>
69
    /* openssl headers end, wolfssl internal headers next */
70
#endif
71
72
#include <wolfssl/wolfcrypt/wc_encrypt.h>
73
74
#ifndef NO_RSA
75
    #include <wolfssl/wolfcrypt/rsa.h>
76
#endif
77
78
#ifdef OPENSSL_EXTRA
79
    /* openssl headers begin */
80
    #include <wolfssl/openssl/ssl.h>
81
    #include <wolfssl/openssl/aes.h>
82
#ifndef WOLFCRYPT_ONLY
83
    #include <wolfssl/openssl/hmac.h>
84
    #include <wolfssl/openssl/cmac.h>
85
#endif
86
    #include <wolfssl/openssl/crypto.h>
87
    #include <wolfssl/openssl/des.h>
88
    #include <wolfssl/openssl/bn.h>
89
    #include <wolfssl/openssl/buffer.h>
90
    #include <wolfssl/openssl/dh.h>
91
    #include <wolfssl/openssl/rsa.h>
92
    #include <wolfssl/openssl/fips_rand.h>
93
#ifndef WOLFCRYPT_ONLY
94
    #include <wolfssl/openssl/pem.h>
95
#endif
96
    #include <wolfssl/openssl/ec.h>
97
    #include <wolfssl/openssl/ec25519.h>
98
    #include <wolfssl/openssl/ed25519.h>
99
    #include <wolfssl/openssl/ec448.h>
100
    #include <wolfssl/openssl/ed448.h>
101
    #include <wolfssl/openssl/ecdsa.h>
102
    #include <wolfssl/openssl/ecdh.h>
103
    #include <wolfssl/openssl/err.h>
104
    #include <wolfssl/openssl/modes.h>
105
    #include <wolfssl/openssl/opensslv.h>
106
    #include <wolfssl/openssl/rc4.h>
107
    #include <wolfssl/openssl/stack.h>
108
    #include <wolfssl/openssl/x509_vfy.h>
109
    /* openssl headers end, wolfssl internal headers next */
110
    #include <wolfssl/wolfcrypt/hmac.h>
111
    #include <wolfssl/wolfcrypt/random.h>
112
    #include <wolfssl/wolfcrypt/des3.h>
113
    #include <wolfssl/wolfcrypt/ecc.h>
114
    #include <wolfssl/wolfcrypt/md4.h>
115
    #include <wolfssl/wolfcrypt/md5.h>
116
    #include <wolfssl/wolfcrypt/arc4.h>
117
    #include <wolfssl/wolfcrypt/curve25519.h>
118
    #include <wolfssl/wolfcrypt/ed25519.h>
119
    #include <wolfssl/wolfcrypt/curve448.h>
120
    #if defined(HAVE_PQC)
121
    #if defined(HAVE_FALCON)
122
        #include <wolfssl/wolfcrypt/falcon.h>
123
    #endif /* HAVE_FALCON */
124
    #if defined(HAVE_DILITHIUM)
125
        #include <wolfssl/wolfcrypt/dilithium.h>
126
    #endif /* HAVE_DILITHIUM */
127
    #endif /* HAVE_PQC */
128
    #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
129
        #ifdef HAVE_OCSP
130
            #include <wolfssl/openssl/ocsp.h>
131
        #endif
132
        #include <wolfssl/openssl/lhash.h>
133
        #include <wolfssl/openssl/txt_db.h>
134
    #endif /* WITH_STUNNEL */
135
    #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
136
        #include <wolfssl/wolfcrypt/sha512.h>
137
    #endif
138
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
139
        && !defined(WC_NO_RNG)
140
        #include <wolfssl/wolfcrypt/srp.h>
141
    #endif
142
    #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST)
143
        #include <wolfssl/wolfcrypt/pkcs7.h>
144
    #endif
145
    #if defined(OPENSSL_ALL) && defined(HAVE_PKCS7)
146
        #include <wolfssl/openssl/pkcs7.h>
147
    #endif /* OPENSSL_ALL && HAVE_PKCS7 */
148
#endif
149
150
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
151
    #include <wolfssl/openssl/x509v3.h>
152
    int SetIndividualInternal(WOLFSSL_BIGNUM* bn, mp_int* mpi);
153
    int SetIndividualExternal(WOLFSSL_BIGNUM** bn, mp_int* mpi);
154
#endif
155
156
#if defined(WOLFSSL_QT)
157
    #include <wolfssl/wolfcrypt/sha.h>
158
#endif
159
160
#ifdef NO_ASN
161
    #include <wolfssl/wolfcrypt/dh.h>
162
#endif
163
#endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
164
165
/*
166
 * OPENSSL_COMPATIBLE_DEFAULTS:
167
 *     Enable default behaviour that is compatible with OpenSSL. For example
168
 *     SSL_CTX by default doesn't verify the loaded certs. Enabling this
169
 *     should make porting to new projects easier.
170
 * WOLFSSL_CHECK_ALERT_ON_ERR:
171
 *     Check for alerts during the handshake in the event of an error.
172
 * NO_SESSION_CACHE_REF:
173
 *     wolfSSL_get_session on a client will return a reference to the internal
174
 *     ClientCache by default for backwards compatibility. This define will
175
 *     make wolfSSL_get_session return a reference to ssl->session. The returned
176
 *     pointer will be freed with the related WOLFSSL object.
177
 */
178
179
#define WOLFSSL_EVP_INCLUDED
180
#include "wolfcrypt/src/evp.c"
181
182
#ifndef WOLFCRYPT_ONLY
183
184
#define WOLFSSL_PK_INCLUDED
185
#include "src/pk.c"
186
187
#ifdef OPENSSL_EXTRA
188
    /* Global pointer to constant BN on */
189
    static WOLFSSL_BIGNUM* bn_one = NULL;
190
191
    /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
192
     *                OPENSSL_EXTRA where RAND callbacks are not used */
193
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
194
        static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
195
        static int gRandMethodsInit = 0;
196
        static wolfSSL_Mutex gRandMethodMutex;
197
    #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
198
#endif /* OPENSSL_EXTRA */
199
200
#if defined(OPENSSL_EXTRA) && defined(HAVE_ECC)
201
const WOLF_EC_NIST_NAME kNistCurves[] = {
202
    {XSTR_SIZEOF("P-192"),   "P-192",   NID_X9_62_prime192v1},
203
    {XSTR_SIZEOF("P-256"),   "P-256",   NID_X9_62_prime256v1},
204
    {XSTR_SIZEOF("P-112"),   "P-112",   NID_secp112r1},
205
    {XSTR_SIZEOF("P-112-2"), "P-112-2", NID_secp112r2},
206
    {XSTR_SIZEOF("P-128"),   "P-128",   NID_secp128r1},
207
    {XSTR_SIZEOF("P-128-2"), "P-128-2", NID_secp128r2},
208
    {XSTR_SIZEOF("P-160"),   "P-160",   NID_secp160r1},
209
    {XSTR_SIZEOF("P-160-2"), "P-160-2", NID_secp160r2},
210
    {XSTR_SIZEOF("P-224"),   "P-224",   NID_secp224r1},
211
    {XSTR_SIZEOF("P-384"),   "P-384",   NID_secp384r1},
212
    {XSTR_SIZEOF("P-521"),   "P-521",   NID_secp521r1},
213
    {XSTR_SIZEOF("K-160"),   "K-160",   NID_secp160k1},
214
    {XSTR_SIZEOF("K-192"),   "K-192",   NID_secp192k1},
215
    {XSTR_SIZEOF("K-224"),   "K-224",   NID_secp224k1},
216
    {XSTR_SIZEOF("K-256"),   "K-256",   NID_secp256k1},
217
    {XSTR_SIZEOF("B-160"),   "B-160",   NID_brainpoolP160r1},
218
    {XSTR_SIZEOF("B-192"),   "B-192",   NID_brainpoolP192r1},
219
    {XSTR_SIZEOF("B-224"),   "B-224",   NID_brainpoolP224r1},
220
    {XSTR_SIZEOF("B-256"),   "B-256",   NID_brainpoolP256r1},
221
    {XSTR_SIZEOF("B-320"),   "B-320",   NID_brainpoolP320r1},
222
    {XSTR_SIZEOF("B-384"),   "B-384",   NID_brainpoolP384r1},
223
    {XSTR_SIZEOF("B-512"),   "B-512",   NID_brainpoolP512r1},
224
#ifdef HAVE_PQC
225
    {XSTR_SIZEOF("KYBER_LEVEL1"), "KYBER_LEVEL1", WOLFSSL_KYBER_LEVEL1},
226
    {XSTR_SIZEOF("KYBER_LEVEL3"), "KYBER_LEVEL3", WOLFSSL_KYBER_LEVEL3},
227
    {XSTR_SIZEOF("KYBER_LEVEL5"), "KYBER_LEVEL5", WOLFSSL_KYBER_LEVEL5},
228
#ifdef HAVE_LIBOQS
229
    {XSTR_SIZEOF("NTRU_HPS_LEVEL1"), "NTRU_HPS_LEVEL1", WOLFSSL_NTRU_HPS_LEVEL1},
230
    {XSTR_SIZEOF("NTRU_HPS_LEVEL3"), "NTRU_HPS_LEVEL3", WOLFSSL_NTRU_HPS_LEVEL3},
231
    {XSTR_SIZEOF("NTRU_HPS_LEVEL5"), "NTRU_HPS_LEVEL5", WOLFSSL_NTRU_HPS_LEVEL5},
232
    {XSTR_SIZEOF("NTRU_HRSS_LEVEL3"), "NTRU_HRSS_LEVEL3", WOLFSSL_NTRU_HRSS_LEVEL3},
233
    {XSTR_SIZEOF("SABER_LEVEL1"), "SABER_LEVEL1", WOLFSSL_SABER_LEVEL1},
234
    {XSTR_SIZEOF("SABER_LEVEL3"), "SABER_LEVEL3", WOLFSSL_SABER_LEVEL3},
235
    {XSTR_SIZEOF("SABER_LEVEL5"), "SABER_LEVEL5", WOLFSSL_SABER_LEVEL5},
236
    {XSTR_SIZEOF("KYBER_90S_LEVEL1"), "KYBER_90S_LEVEL1", WOLFSSL_KYBER_90S_LEVEL1},
237
    {XSTR_SIZEOF("KYBER_90S_LEVEL3"), "KYBER_90S_LEVEL3", WOLFSSL_KYBER_90S_LEVEL3},
238
    {XSTR_SIZEOF("KYBER_90S_LEVEL5"), "KYBER_90S_LEVEL5", WOLFSSL_KYBER_90S_LEVEL5},
239
    {XSTR_SIZEOF("P256_NTRU_HPS_LEVEL1"), "P256_NTRU_HPS_LEVEL1", WOLFSSL_P256_NTRU_HPS_LEVEL1},
240
    {XSTR_SIZEOF("P384_NTRU_HPS_LEVEL3"), "P384_NTRU_HPS_LEVEL3", WOLFSSL_P384_NTRU_HPS_LEVEL3},
241
    {XSTR_SIZEOF("P521_NTRU_HPS_LEVEL5"), "P521_NTRU_HPS_LEVEL5", WOLFSSL_P521_NTRU_HPS_LEVEL5},
242
    {XSTR_SIZEOF("P384_NTRU_HRSS_LEVEL3"), "P384_NTRU_HRSS_LEVEL3", WOLFSSL_P384_NTRU_HRSS_LEVEL3},
243
    {XSTR_SIZEOF("P256_SABER_LEVEL1"), "P256_SABER_LEVEL1", WOLFSSL_P256_SABER_LEVEL1},
244
    {XSTR_SIZEOF("P384_SABER_LEVEL3"), "P384_SABER_LEVEL3", WOLFSSL_P384_SABER_LEVEL3},
245
    {XSTR_SIZEOF("P521_SABER_LEVEL5"), "P521_SABER_LEVEL5", WOLFSSL_P521_SABER_LEVEL5},
246
    {XSTR_SIZEOF("P256_KYBER_LEVEL1"), "P256_KYBER_LEVEL1", WOLFSSL_P256_KYBER_LEVEL1},
247
    {XSTR_SIZEOF("P384_KYBER_LEVEL3"), "P384_KYBER_LEVEL3", WOLFSSL_P384_KYBER_LEVEL3},
248
    {XSTR_SIZEOF("P521_KYBER_LEVEL5"), "P521_KYBER_LEVEL5", WOLFSSL_P521_KYBER_LEVEL5},
249
    {XSTR_SIZEOF("P256_KYBER_90S_LEVEL1"), "P256_KYBER_90S_LEVEL1", WOLFSSL_P256_KYBER_90S_LEVEL1},
250
    {XSTR_SIZEOF("P384_KYBER_90S_LEVEL3"), "P384_KYBER_90S_LEVEL3", WOLFSSL_P384_KYBER_90S_LEVEL3},
251
    {XSTR_SIZEOF("P521_KYBER_90S_LEVEL5"), "P521_KYBER_90S_LEVEL5", WOLFSSL_P521_KYBER_90S_LEVEL5},
252
#endif
253
#endif
254
    {0, NULL, 0},
255
};
256
#endif
257
258
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
259
#include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
260
#endif
261
262
#ifdef WOLFSSL_SESSION_EXPORT
263
/* Used to import a serialized TLS session.
264
 * WARNING: buf contains sensitive information about the state and is best to be
265
 *          encrypted before storing if stored.
266
 *
267
 * @param ssl WOLFSSL structure to import the session into
268
 * @param buf serialized session
269
 * @param sz  size of buffer 'buf'
270
 * @return the number of bytes read from buffer 'buf'
271
 */
272
int wolfSSL_tls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
273
{
274
    if (ssl == NULL || buf == NULL) {
275
        return BAD_FUNC_ARG;
276
    }
277
    return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
278
}
279
280
281
/* Used to export a serialized TLS session.
282
 * WARNING: buf contains sensitive information about the state and is best to be
283
 *          encrypted before storing if stored.
284
 *
285
 * @param ssl WOLFSSL structure to export the session from
286
 * @param buf output of serialized session
287
 * @param sz  size in bytes set in 'buf'
288
 * @return the number of bytes written into buffer 'buf'
289
 */
290
int wolfSSL_tls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
291
{
292
    if (ssl == NULL || sz == NULL) {
293
        return BAD_FUNC_ARG;
294
    }
295
    return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
296
}
297
298
#ifdef WOLFSSL_DTLS
299
int wolfSSL_dtls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
300
{
301
    WOLFSSL_ENTER("wolfSSL_session_import");
302
303
    if (ssl == NULL || buf == NULL) {
304
        return BAD_FUNC_ARG;
305
    }
306
307
    /* sanity checks on buffer and protocol are done in internal function */
308
    return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
309
}
310
311
312
/* Sets the function to call for serializing the session. This function is
313
 * called right after the handshake is completed. */
314
int wolfSSL_CTX_dtls_set_export(WOLFSSL_CTX* ctx, wc_dtls_export func)
315
{
316
317
    WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_export");
318
319
    /* purposefully allow func to be NULL */
320
    if (ctx == NULL) {
321
        return BAD_FUNC_ARG;
322
    }
323
324
    ctx->dtls_export = func;
325
326
    return WOLFSSL_SUCCESS;
327
}
328
329
330
/* Sets the function in WOLFSSL struct to call for serializing the session. This
331
 * function is called right after the handshake is completed. */
332
int wolfSSL_dtls_set_export(WOLFSSL* ssl, wc_dtls_export func)
333
{
334
335
    WOLFSSL_ENTER("wolfSSL_dtls_set_export");
336
337
    /* purposefully allow func to be NULL */
338
    if (ssl == NULL) {
339
        return BAD_FUNC_ARG;
340
    }
341
342
    ssl->dtls_export = func;
343
344
    return WOLFSSL_SUCCESS;
345
}
346
347
348
/* This function allows for directly serializing a session rather than using
349
 * callbacks. It has less overhead by removing a temporary buffer and gives
350
 * control over when the session gets serialized. When using callbacks the
351
 * session is always serialized immediately after the handshake is finished.
352
 *
353
 * buf is the argument to contain the serialized session
354
 * sz  is the size of the buffer passed in
355
 * ssl is the WOLFSSL struct to serialize
356
 * returns the size of serialized session on success, 0 on no action, and
357
 *         negative value on error */
358
int wolfSSL_dtls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
359
{
360
    WOLFSSL_ENTER("wolfSSL_dtls_export");
361
362
    if (ssl == NULL || sz == NULL) {
363
        return BAD_FUNC_ARG;
364
    }
365
366
    if (buf == NULL) {
367
        *sz = MAX_EXPORT_BUFFER;
368
        return 0;
369
    }
370
371
    /* if not DTLS do nothing */
372
    if (!ssl->options.dtls) {
373
        WOLFSSL_MSG("Currently only DTLS export is supported");
374
        return 0;
375
    }
376
377
    /* copy over keys, options, and dtls state struct */
378
    return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
379
}
380
381
382
/* This function is similar to wolfSSL_dtls_export but only exports the portion
383
 * of the WOLFSSL structure related to the state of the connection, i.e. peer
384
 * sequence number, epoch, AEAD state etc.
385
 *
386
 * buf is the argument to contain the serialized state, if null then set "sz" to
387
 *     buffer size required
388
 * sz  is the size of the buffer passed in
389
 * ssl is the WOLFSSL struct to serialize
390
 * returns the size of serialized session on success, 0 on no action, and
391
 *         negative value on error */
392
int wolfSSL_dtls_export_state_only(WOLFSSL* ssl, unsigned char* buf,
393
        unsigned int* sz)
394
{
395
    WOLFSSL_ENTER("wolfSSL_dtls_export_state_only");
396
397
    if (ssl == NULL || sz == NULL) {
398
        return BAD_FUNC_ARG;
399
    }
400
401
    if (buf == NULL) {
402
        *sz = MAX_EXPORT_STATE_BUFFER;
403
        return 0;
404
    }
405
406
    /* if not DTLS do nothing */
407
    if (!ssl->options.dtls) {
408
        WOLFSSL_MSG("Currently only DTLS export state is supported");
409
        return 0;
410
    }
411
412
    /* copy over keys, options, and dtls state struct */
413
    return wolfSSL_dtls_export_state_internal(ssl, buf, *sz);
414
}
415
416
417
/* returns 0 on success */
418
int wolfSSL_send_session(WOLFSSL* ssl)
419
{
420
    int ret;
421
    byte* buf;
422
    word32 bufSz = MAX_EXPORT_BUFFER;
423
424
    WOLFSSL_ENTER("wolfSSL_send_session");
425
426
    if (ssl == NULL) {
427
        return BAD_FUNC_ARG;
428
    }
429
430
    buf = (byte*)XMALLOC(bufSz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
431
    if (buf == NULL) {
432
        return MEMORY_E;
433
    }
434
435
    /* if not DTLS do nothing */
436
    if (!ssl->options.dtls) {
437
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
438
        WOLFSSL_MSG("Currently only DTLS export is supported");
439
        return 0;
440
    }
441
442
    /* copy over keys, options, and dtls state struct */
443
    ret = wolfSSL_session_export_internal(ssl, buf, &bufSz, WOLFSSL_EXPORT_DTLS);
444
    if (ret < 0) {
445
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
446
        return ret;
447
    }
448
449
    /* if no error ret has size of buffer */
450
    ret = ssl->dtls_export(ssl, buf, ret, NULL);
451
    if (ret != WOLFSSL_SUCCESS) {
452
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
453
        return ret;
454
    }
455
456
    XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
457
    return 0;
458
}
459
#endif /* WOLFSSL_DTLS */
460
#endif /* WOLFSSL_SESSION_EXPORT */
461
462
/* prevent multiple mutex initializations */
463
static volatile WOLFSSL_GLOBAL int initRefCount = 0;
464
static WOLFSSL_GLOBAL wolfSSL_Mutex count_mutex;   /* init ref count mutex */
465
static WOLFSSL_GLOBAL int count_mutex_valid = 0;
466
467
/* Create a new WOLFSSL_CTX struct and return the pointer to created struct.
468
   WOLFSSL_METHOD pointer passed in is given to ctx to manage.
469
   This function frees the passed in WOLFSSL_METHOD struct on failure and on
470
   success is freed when ctx is freed.
471
 */
472
WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap)
473
0
{
474
0
    WOLFSSL_CTX* ctx = NULL;
475
476
0
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
477
478
0
    if (initRefCount == 0) {
479
        /* user no longer forced to call Init themselves */
480
0
        int ret = wolfSSL_Init();
481
0
        if (ret != WOLFSSL_SUCCESS) {
482
0
            WOLFSSL_MSG("wolfSSL_Init failed");
483
0
            WOLFSSL_LEAVE("WOLFSSL_CTX_new", 0);
484
0
            if (method != NULL) {
485
0
                XFREE(method, heap, DYNAMIC_TYPE_METHOD);
486
0
            }
487
0
            return NULL;
488
0
        }
489
0
    }
490
491
0
    if (method == NULL)
492
0
        return ctx;
493
494
0
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
495
0
    if (ctx) {
496
0
        int ret;
497
498
0
        ret = InitSSL_Ctx(ctx, method, heap);
499
    #ifdef WOLFSSL_STATIC_MEMORY
500
        if (heap != NULL) {
501
            ctx->onHeapHint = 1; /* free the memory back to heap when done */
502
        }
503
    #endif
504
0
        if (ret < 0) {
505
0
            WOLFSSL_MSG("Init CTX failed");
506
0
            wolfSSL_CTX_free(ctx);
507
0
            ctx = NULL;
508
0
        }
509
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
510
                           && !defined(NO_SHA256) && !defined(WC_NO_RNG)
511
        else {
512
            ctx->srp = (Srp*)XMALLOC(sizeof(Srp), heap, DYNAMIC_TYPE_SRP);
513
            if (ctx->srp == NULL){
514
                WOLFSSL_MSG("Init CTX failed");
515
                wolfSSL_CTX_free(ctx);
516
                return NULL;
517
            }
518
            XMEMSET(ctx->srp, 0, sizeof(Srp));
519
        }
520
#endif
521
0
    }
522
0
    else {
523
0
        WOLFSSL_MSG("Alloc CTX failed, method freed");
524
0
        XFREE(method, heap, DYNAMIC_TYPE_METHOD);
525
0
    }
526
527
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
528
    if (ctx) {
529
        wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
530
        wolfSSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
531
        if (wolfSSL_CTX_set_min_proto_version(ctx,
532
                                              (method->version.major == DTLS_MAJOR) ?
533
                                               DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS ||
534
#ifdef HAVE_ANON
535
                wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS ||
536
#endif
537
                wolfSSL_CTX_set_group_messages(ctx) != WOLFSSL_SUCCESS) {
538
            WOLFSSL_MSG("Setting OpenSSL CTX defaults failed");
539
            wolfSSL_CTX_free(ctx);
540
            ctx = NULL;
541
        }
542
    }
543
#endif
544
545
0
    WOLFSSL_LEAVE("WOLFSSL_CTX_new", 0);
546
0
    return ctx;
547
0
}
548
549
550
WOLFSSL_ABI
551
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
552
0
{
553
#ifdef WOLFSSL_HEAP_TEST
554
    /* if testing the heap hint then set top level CTX to have test value */
555
    return wolfSSL_CTX_new_ex(method, (void*)WOLFSSL_HEAP_TEST);
556
#else
557
0
    return wolfSSL_CTX_new_ex(method, NULL);
558
0
#endif
559
0
}
560
561
/* increases CTX reference count to track proper time to "free" */
562
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
563
0
{
564
0
    int refCount = SSL_CTX_RefCount(ctx, 1);
565
0
    return ((refCount > 1) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
566
0
}
567
568
WOLFSSL_ABI
569
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
570
0
{
571
0
    WOLFSSL_ENTER("SSL_CTX_free");
572
0
    if (ctx) {
573
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
574
&& !defined(NO_SHA256) && !defined(WC_NO_RNG)
575
        if (ctx->srp != NULL) {
576
            if (ctx->srp_password != NULL){
577
                XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP);
578
                ctx->srp_password = NULL;
579
            }
580
            wc_SrpTerm(ctx->srp);
581
            XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP);
582
            ctx->srp = NULL;
583
        }
584
#endif
585
0
        FreeSSL_Ctx(ctx);
586
0
    }
587
588
0
    WOLFSSL_LEAVE("SSL_CTX_free", 0);
589
0
}
590
591
592
#ifdef HAVE_ENCRYPT_THEN_MAC
593
/**
594
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
595
 * The default value: enabled.
596
 *
597
 * ctx  SSL/TLS context.
598
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
599
 * returns WOLFSSL_SUCCESS
600
 */
601
int wolfSSL_CTX_AllowEncryptThenMac(WOLFSSL_CTX *ctx, int set)
602
0
{
603
0
    ctx->disallowEncThenMac = !set;
604
0
    return WOLFSSL_SUCCESS;
605
0
}
606
607
/**
608
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
609
 * The default value comes from context.
610
 *
611
 * ctx  SSL/TLS context.
612
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
613
 * returns WOLFSSL_SUCCESS
614
 */
615
int wolfSSL_AllowEncryptThenMac(WOLFSSL *ssl, int set)
616
0
{
617
0
    ssl->options.disallowEncThenMac = !set;
618
0
    return WOLFSSL_SUCCESS;
619
0
}
620
#endif
621
622
#ifdef SINGLE_THREADED
623
/* no locking in single threaded mode, allow a CTX level rng to be shared with
624
 * WOLFSSL objects, WOLFSSL_SUCCESS on ok */
625
int wolfSSL_CTX_new_rng(WOLFSSL_CTX* ctx)
626
{
627
    WC_RNG* rng;
628
    int     ret;
629
630
    if (ctx == NULL) {
631
        return BAD_FUNC_ARG;
632
    }
633
634
    rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ctx->heap, DYNAMIC_TYPE_RNG);
635
    if (rng == NULL) {
636
        return MEMORY_E;
637
    }
638
639
#ifndef HAVE_FIPS
640
    ret = wc_InitRng_ex(rng, ctx->heap, ctx->devId);
641
#else
642
    ret = wc_InitRng(rng);
643
#endif
644
    if (ret != 0) {
645
        XFREE(rng, ctx->heap, DYNAMIC_TYPE_RNG);
646
        return ret;
647
    }
648
649
    ctx->rng = rng;
650
    return WOLFSSL_SUCCESS;
651
}
652
#endif
653
654
655
WOLFSSL_ABI
656
WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx)
657
0
{
658
0
    WOLFSSL* ssl = NULL;
659
0
    int ret = 0;
660
661
0
    WOLFSSL_ENTER("SSL_new");
662
663
0
    if (ctx == NULL)
664
0
        return ssl;
665
666
0
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
667
0
    if (ssl)
668
0
        if ( (ret = InitSSL(ssl, ctx, 0)) < 0) {
669
0
            FreeSSL(ssl, ctx->heap);
670
0
            ssl = 0;
671
0
        }
672
673
0
    WOLFSSL_LEAVE("SSL_new", ret);
674
0
    (void)ret;
675
676
0
    return ssl;
677
0
}
678
679
680
WOLFSSL_ABI
681
void wolfSSL_free(WOLFSSL* ssl)
682
0
{
683
0
    WOLFSSL_ENTER("SSL_free");
684
0
    if (ssl)
685
0
        FreeSSL(ssl, ssl->ctx->heap);
686
0
    WOLFSSL_LEAVE("SSL_free", 0);
687
0
}
688
689
690
int wolfSSL_is_server(WOLFSSL* ssl)
691
0
{
692
0
    if (ssl == NULL)
693
0
        return BAD_FUNC_ARG;
694
0
    return ssl->options.side == WOLFSSL_SERVER_END;
695
0
}
696
697
#ifdef HAVE_WRITE_DUP
698
699
/*
700
 * Release resources around WriteDup object
701
 *
702
 * ssl WOLFSSL object
703
 *
704
 * no return, destruction so make best attempt
705
*/
706
void FreeWriteDup(WOLFSSL* ssl)
707
{
708
    int doFree = 0;
709
710
    WOLFSSL_ENTER("FreeWriteDup");
711
712
    if (ssl->dupWrite) {
713
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) == 0) {
714
            ssl->dupWrite->dupCount--;
715
            if (ssl->dupWrite->dupCount == 0) {
716
                doFree = 1;
717
            } else {
718
                WOLFSSL_MSG("WriteDup count not zero, no full free");
719
            }
720
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
721
        }
722
    }
723
724
    if (doFree) {
725
        WOLFSSL_MSG("Doing WriteDup full free, count to zero");
726
        wc_FreeMutex(&ssl->dupWrite->dupMutex);
727
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
728
    }
729
}
730
731
732
/*
733
 * duplicate existing ssl members into dup needed for writing
734
 *
735
 * dup write only WOLFSSL
736
 * ssl existing WOLFSSL
737
 *
738
 * 0 on success
739
*/
740
static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
741
{
742
    /* shared dupWrite setup */
743
    ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
744
                                       DYNAMIC_TYPE_WRITEDUP);
745
    if (ssl->dupWrite == NULL) {
746
        return MEMORY_E;
747
    }
748
    XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
749
750
    if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
751
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
752
        ssl->dupWrite = NULL;
753
        return BAD_MUTEX_E;
754
    }
755
    ssl->dupWrite->dupCount = 2;    /* both sides have a count to start */
756
    dup->dupWrite = ssl->dupWrite; /* each side uses */
757
758
    /* copy write parts over to dup writer */
759
    XMEMCPY(&dup->specs,   &ssl->specs,   sizeof(CipherSpecs));
760
    XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
761
    XMEMCPY(&dup->keys,    &ssl->keys,    sizeof(Keys));
762
    XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
763
    XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
764
    XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
765
766
    /* dup side now owns encrypt/write ciphers */
767
    XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
768
769
    dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
770
    dup->CBIOSend = ssl->CBIOSend;
771
#ifdef OPENSSL_EXTRA
772
    dup->cbioFlag = ssl->cbioFlag;
773
#endif
774
    dup->wfd    = ssl->wfd;
775
    dup->wflags = ssl->wflags;
776
#ifndef WOLFSSL_AEAD_ONLY
777
    dup->hmac   = ssl->hmac;
778
#endif
779
#ifdef HAVE_TRUNCATED_HMAC
780
    dup->truncated_hmac = ssl->truncated_hmac;
781
#endif
782
783
    /* unique side dup setup */
784
    dup->dupSide = WRITE_DUP_SIDE;
785
    ssl->dupSide = READ_DUP_SIDE;
786
787
    return 0;
788
}
789
790
791
/*
792
 * duplicate a WOLFSSL object post handshake for writing only
793
 * turn existing object into read only.  Allows concurrent access from two
794
 * different threads.
795
 *
796
 * ssl existing WOLFSSL object
797
 *
798
 * return dup'd WOLFSSL object on success
799
*/
800
WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
801
{
802
    WOLFSSL* dup = NULL;
803
    int ret = 0;
804
805
    (void)ret;
806
    WOLFSSL_ENTER("wolfSSL_write_dup");
807
808
    if (ssl == NULL) {
809
        return ssl;
810
    }
811
812
    if (ssl->options.handShakeDone == 0) {
813
        WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
814
        return NULL;
815
    }
816
817
    if (ssl->dupWrite) {
818
        WOLFSSL_MSG("wolfSSL_write_dup already called once");
819
        return NULL;
820
    }
821
822
    dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
823
    if (dup) {
824
        if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
825
            FreeSSL(dup, ssl->ctx->heap);
826
            dup = NULL;
827
        } else if ( (ret = DupSSL(dup, ssl)) < 0) {
828
            FreeSSL(dup, ssl->ctx->heap);
829
            dup = NULL;
830
        }
831
    }
832
833
    WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
834
835
    return dup;
836
}
837
838
839
/*
840
 * Notify write dup side of fatal error or close notify
841
 *
842
 * ssl WOLFSSL object
843
 * err Notify err
844
 *
845
 * 0 on success
846
*/
847
int NotifyWriteSide(WOLFSSL* ssl, int err)
848
{
849
    int ret;
850
851
    WOLFSSL_ENTER("NotifyWriteSide");
852
853
    ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
854
    if (ret == 0) {
855
        ssl->dupWrite->dupErr = err;
856
        ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
857
    }
858
859
    return ret;
860
}
861
862
863
#endif /* HAVE_WRITE_DUP */
864
865
866
#ifdef HAVE_POLY1305
867
/* set if to use old poly 1 for yes 0 to use new poly */
868
int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
869
0
{
870
0
    (void)ssl;
871
0
    (void)value;
872
873
0
#ifndef WOLFSSL_NO_TLS12
874
0
    WOLFSSL_ENTER("SSL_use_old_poly");
875
0
    WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
876
0
            "is depreciated");
877
0
    ssl->options.oldPoly = (word16)value;
878
0
    WOLFSSL_LEAVE("SSL_use_old_poly", 0);
879
0
#endif
880
0
    return 0;
881
0
}
882
#endif
883
884
885
WOLFSSL_ABI
886
int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
887
0
{
888
0
    int ret;
889
890
0
    WOLFSSL_ENTER("SSL_set_fd");
891
892
0
    if (ssl == NULL) {
893
0
        return BAD_FUNC_ARG;
894
0
    }
895
896
0
    ret = wolfSSL_set_read_fd(ssl, fd);
897
0
    if (ret == WOLFSSL_SUCCESS) {
898
0
        ret = wolfSSL_set_write_fd(ssl, fd);
899
0
    }
900
901
0
    return ret;
902
0
}
903
904
#ifdef WOLFSSL_DTLS
905
int wolfSSL_set_dtls_fd_connected(WOLFSSL* ssl, int fd)
906
{
907
    int ret;
908
909
    WOLFSSL_ENTER("SSL_set_dtls_fd_connected");
910
911
    if (ssl == NULL) {
912
        return BAD_FUNC_ARG;
913
    }
914
915
    ret = wolfSSL_set_fd(ssl, fd);
916
    if (ret == WOLFSSL_SUCCESS)
917
        ssl->buffers.dtlsCtx.connected = 1;
918
919
    return ret;
920
}
921
#endif
922
923
924
int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
925
0
{
926
0
    WOLFSSL_ENTER("SSL_set_read_fd");
927
928
0
    if (ssl == NULL) {
929
0
        return BAD_FUNC_ARG;
930
0
    }
931
932
0
    ssl->rfd = fd;      /* not used directly to allow IO callbacks */
933
0
    ssl->IOCB_ReadCtx  = &ssl->rfd;
934
935
    #ifdef WOLFSSL_DTLS
936
        ssl->buffers.dtlsCtx.connected = 0;
937
        if (ssl->options.dtls) {
938
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
939
            ssl->buffers.dtlsCtx.rfd = fd;
940
        }
941
    #endif
942
943
0
    WOLFSSL_LEAVE("SSL_set_read_fd", WOLFSSL_SUCCESS);
944
0
    return WOLFSSL_SUCCESS;
945
0
}
946
947
948
int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
949
0
{
950
0
    WOLFSSL_ENTER("SSL_set_write_fd");
951
952
0
    if (ssl == NULL) {
953
0
        return BAD_FUNC_ARG;
954
0
    }
955
956
0
    ssl->wfd = fd;      /* not used directly to allow IO callbacks */
957
0
    ssl->IOCB_WriteCtx  = &ssl->wfd;
958
959
    #ifdef WOLFSSL_DTLS
960
        ssl->buffers.dtlsCtx.connected = 0;
961
        if (ssl->options.dtls) {
962
            ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
963
            ssl->buffers.dtlsCtx.wfd = fd;
964
        }
965
    #endif
966
967
0
    WOLFSSL_LEAVE("SSL_set_write_fd", WOLFSSL_SUCCESS);
968
0
    return WOLFSSL_SUCCESS;
969
0
}
970
971
972
/**
973
  * Get the name of cipher at priority level passed in.
974
  */
975
char* wolfSSL_get_cipher_list(int priority)
976
0
{
977
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
978
979
0
    if (priority >= GetCipherNamesSize() || priority < 0) {
980
0
        return 0;
981
0
    }
982
983
0
    return (char*)ciphers[priority].name;
984
0
}
985
986
987
/**
988
  * Get the name of cipher at priority level passed in.
989
  */
990
char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
991
0
{
992
993
0
    if (ssl == NULL) {
994
0
        return NULL;
995
0
    }
996
0
    else {
997
0
        const char* cipher;
998
999
0
        if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
1000
0
            if (priority == 0) {
1001
0
                return (char*)cipher;
1002
0
            }
1003
0
            else {
1004
0
                return NULL;
1005
0
            }
1006
0
        }
1007
0
        else {
1008
0
            return wolfSSL_get_cipher_list(priority);
1009
0
        }
1010
0
    }
1011
0
}
1012
1013
1014
int wolfSSL_get_ciphers(char* buf, int len)
1015
0
{
1016
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1017
0
    int ciphersSz = GetCipherNamesSize();
1018
0
    int i;
1019
0
    int cipherNameSz;
1020
1021
0
    if (buf == NULL || len <= 0)
1022
0
        return BAD_FUNC_ARG;
1023
1024
    /* Add each member to the buffer delimited by a : */
1025
0
    for (i = 0; i < ciphersSz; i++) {
1026
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name);
1027
0
        if (cipherNameSz + 1 < len) {
1028
0
            XSTRNCPY(buf, ciphers[i].name, len);
1029
0
            buf += cipherNameSz;
1030
1031
0
            if (i < ciphersSz - 1)
1032
0
                *buf++ = ':';
1033
0
            *buf = 0;
1034
1035
0
            len -= cipherNameSz + 1;
1036
0
        }
1037
0
        else
1038
0
            return BUFFER_E;
1039
0
    }
1040
0
    return WOLFSSL_SUCCESS;
1041
0
}
1042
1043
1044
#ifndef NO_ERROR_STRINGS
1045
/* places a list of all supported cipher suites in TLS_* format into "buf"
1046
 * return WOLFSSL_SUCCESS on success */
1047
int wolfSSL_get_ciphers_iana(char* buf, int len)
1048
0
{
1049
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1050
0
    int ciphersSz = GetCipherNamesSize();
1051
0
    int i;
1052
0
    int cipherNameSz;
1053
1054
0
    if (buf == NULL || len <= 0)
1055
0
        return BAD_FUNC_ARG;
1056
1057
    /* Add each member to the buffer delimited by a : */
1058
0
    for (i = 0; i < ciphersSz; i++) {
1059
0
#ifndef NO_CIPHER_SUITE_ALIASES
1060
0
        if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
1061
0
            continue;
1062
0
#endif
1063
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
1064
0
        if (cipherNameSz + 1 < len) {
1065
0
            XSTRNCPY(buf, ciphers[i].name_iana, len);
1066
0
            buf += cipherNameSz;
1067
1068
0
            if (i < ciphersSz - 1)
1069
0
                *buf++ = ':';
1070
0
            *buf = 0;
1071
1072
0
            len -= cipherNameSz + 1;
1073
0
        }
1074
0
        else
1075
0
            return BUFFER_E;
1076
0
    }
1077
0
    return WOLFSSL_SUCCESS;
1078
0
}
1079
#endif /* NO_ERROR_STRINGS */
1080
1081
1082
const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
1083
0
{
1084
0
    const char* cipher;
1085
1086
0
    if (ssl == NULL)
1087
0
        return NULL;
1088
1089
0
    cipher = wolfSSL_get_cipher_name_iana(ssl);
1090
0
    len = min(len, (int)(XSTRLEN(cipher) + 1));
1091
0
    XMEMCPY(buf, cipher, len);
1092
0
    return buf;
1093
0
}
1094
1095
int wolfSSL_get_fd(const WOLFSSL* ssl)
1096
0
{
1097
0
    int fd = -1;
1098
0
    WOLFSSL_ENTER("SSL_get_fd");
1099
0
    if (ssl) {
1100
0
        fd = ssl->rfd;
1101
0
    }
1102
0
    WOLFSSL_LEAVE("SSL_get_fd", fd);
1103
0
    return fd;
1104
0
}
1105
1106
1107
int wolfSSL_dtls(WOLFSSL* ssl)
1108
0
{
1109
0
    int dtlsOpt = 0;
1110
0
    if (ssl)
1111
0
        dtlsOpt = ssl->options.dtls;
1112
0
    return dtlsOpt;
1113
0
}
1114
1115
#if !defined(NO_CERTS)
1116
/* Set whether mutual authentication is required for connections.
1117
 * Server side only.
1118
 *
1119
 * ctx  The SSL/TLS CTX object.
1120
 * req  1 to indicate required and 0 when not.
1121
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
1122
 * 0 on success.
1123
 */
1124
int wolfSSL_CTX_mutual_auth(WOLFSSL_CTX* ctx, int req)
1125
0
{
1126
0
    if (ctx == NULL)
1127
0
        return BAD_FUNC_ARG;
1128
0
    if (ctx->method->side == WOLFSSL_CLIENT_END)
1129
0
        return SIDE_ERROR;
1130
1131
0
    ctx->mutualAuth = (byte)req;
1132
1133
0
    return 0;
1134
0
}
1135
1136
/* Set whether mutual authentication is required for the connection.
1137
 * Server side only.
1138
 *
1139
 * ssl  The SSL/TLS object.
1140
 * req  1 to indicate required and 0 when not.
1141
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
1142
 * SIDE_ERROR when not a client and 0 on success.
1143
 */
1144
int wolfSSL_mutual_auth(WOLFSSL* ssl, int req)
1145
0
{
1146
0
    if (ssl == NULL)
1147
0
        return BAD_FUNC_ARG;
1148
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
1149
0
        return SIDE_ERROR;
1150
1151
0
    ssl->options.mutualAuth = (word16)req;
1152
1153
0
    return 0;
1154
0
}
1155
#endif /* NO_CERTS */
1156
1157
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
1158
1159
int wolfSSL_CTX_set_AcceptFilter(
1160
    WOLFSSL_CTX *ctx,
1161
    NetworkFilterCallback_t AcceptFilter,
1162
    void *AcceptFilter_arg)
1163
{
1164
    if (ctx == NULL)
1165
        return BAD_FUNC_ARG;
1166
    ctx->AcceptFilter = AcceptFilter;
1167
    ctx->AcceptFilter_arg = AcceptFilter_arg;
1168
    return 0;
1169
}
1170
1171
int wolfSSL_set_AcceptFilter(
1172
    WOLFSSL *ssl,
1173
    NetworkFilterCallback_t AcceptFilter,
1174
    void *AcceptFilter_arg)
1175
{
1176
    if (ssl == NULL)
1177
        return BAD_FUNC_ARG;
1178
    ssl->AcceptFilter = AcceptFilter;
1179
    ssl->AcceptFilter_arg = AcceptFilter_arg;
1180
    return 0;
1181
}
1182
1183
int wolfSSL_CTX_set_ConnectFilter(
1184
    WOLFSSL_CTX *ctx,
1185
    NetworkFilterCallback_t ConnectFilter,
1186
    void *ConnectFilter_arg)
1187
{
1188
    if (ctx == NULL)
1189
        return BAD_FUNC_ARG;
1190
    ctx->ConnectFilter = ConnectFilter;
1191
    ctx->ConnectFilter_arg = ConnectFilter_arg;
1192
    return 0;
1193
}
1194
1195
int wolfSSL_set_ConnectFilter(
1196
    WOLFSSL *ssl,
1197
    NetworkFilterCallback_t ConnectFilter,
1198
    void *ConnectFilter_arg)
1199
{
1200
    if (ssl == NULL)
1201
        return BAD_FUNC_ARG;
1202
    ssl->ConnectFilter = ConnectFilter;
1203
    ssl->ConnectFilter_arg = ConnectFilter_arg;
1204
    return 0;
1205
}
1206
1207
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
1208
1209
#ifndef WOLFSSL_LEANPSK
1210
#if defined(WOLFSSL_DTLS) && defined(XINET_PTON) && \
1211
    !defined(WOLFSSL_NO_SOCK) && defined(HAVE_SOCKADDR)
1212
void* wolfSSL_dtls_create_peer(int port, char* ip)
1213
{
1214
    SOCKADDR_IN *addr;
1215
    addr = (SOCKADDR_IN*)XMALLOC(sizeof(*addr), NULL,
1216
            DYNAMIC_TYPE_SOCKADDR);
1217
    if (addr == NULL) {
1218
        return NULL;
1219
    }
1220
1221
    addr->sin_family = AF_INET;
1222
    addr->sin_port = XHTONS((word16)port);
1223
    if (XINET_PTON(AF_INET, ip, &addr->sin_addr) < 1) {
1224
        XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1225
        return NULL;
1226
    }
1227
1228
    return addr;
1229
}
1230
1231
int wolfSSL_dtls_free_peer(void* addr)
1232
{
1233
    XFREE(addr, NULL, DYNAMIC_TYPE_SOCKADDR);
1234
    return WOLFSSL_SUCCESS;
1235
}
1236
#endif
1237
1238
int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz)
1239
0
{
1240
#ifdef WOLFSSL_DTLS
1241
    void* sa;
1242
1243
    if (ssl == NULL)
1244
        return WOLFSSL_FAILURE;
1245
1246
    if (peer == NULL || peerSz == 0) {
1247
        if (ssl->buffers.dtlsCtx.peer.sa != NULL)
1248
            XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR);
1249
        ssl->buffers.dtlsCtx.peer.sa = NULL;
1250
        ssl->buffers.dtlsCtx.peer.sz = 0;
1251
        ssl->buffers.dtlsCtx.peer.bufSz = 0;
1252
        ssl->buffers.dtlsCtx.userSet = 0;
1253
        return WOLFSSL_SUCCESS;
1254
    }
1255
1256
    sa = (void*)XMALLOC(peerSz, ssl->heap, DYNAMIC_TYPE_SOCKADDR);
1257
    if (sa != NULL) {
1258
        if (ssl->buffers.dtlsCtx.peer.sa != NULL) {
1259
            XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR);
1260
            ssl->buffers.dtlsCtx.peer.sa = NULL;
1261
        }
1262
        XMEMCPY(sa, peer, peerSz);
1263
        ssl->buffers.dtlsCtx.peer.sa = sa;
1264
        ssl->buffers.dtlsCtx.peer.sz = peerSz;
1265
        ssl->buffers.dtlsCtx.peer.bufSz = peerSz;
1266
        ssl->buffers.dtlsCtx.userSet = 1;
1267
        return WOLFSSL_SUCCESS;
1268
    }
1269
    return WOLFSSL_FAILURE;
1270
#else
1271
0
    (void)ssl;
1272
0
    (void)peer;
1273
0
    (void)peerSz;
1274
0
    return WOLFSSL_NOT_IMPLEMENTED;
1275
0
#endif
1276
0
}
1277
1278
int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz)
1279
0
{
1280
#ifdef WOLFSSL_DTLS
1281
    if (ssl == NULL) {
1282
        return WOLFSSL_FAILURE;
1283
    }
1284
1285
    if (peer != NULL && peerSz != NULL
1286
            && *peerSz >= ssl->buffers.dtlsCtx.peer.sz
1287
            && ssl->buffers.dtlsCtx.peer.sa != NULL) {
1288
        *peerSz = ssl->buffers.dtlsCtx.peer.sz;
1289
        XMEMCPY(peer, ssl->buffers.dtlsCtx.peer.sa, *peerSz);
1290
        return WOLFSSL_SUCCESS;
1291
    }
1292
    return WOLFSSL_FAILURE;
1293
#else
1294
0
    (void)ssl;
1295
0
    (void)peer;
1296
0
    (void)peerSz;
1297
0
    return WOLFSSL_NOT_IMPLEMENTED;
1298
0
#endif
1299
0
}
1300
1301
1302
#if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS)
1303
1304
int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx)
1305
{
1306
    WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_sctp()");
1307
1308
    if (ctx == NULL)
1309
        return BAD_FUNC_ARG;
1310
1311
    ctx->dtlsSctp = 1;
1312
    return WOLFSSL_SUCCESS;
1313
}
1314
1315
1316
int wolfSSL_dtls_set_sctp(WOLFSSL* ssl)
1317
{
1318
    WOLFSSL_ENTER("wolfSSL_dtls_set_sctp()");
1319
1320
    if (ssl == NULL)
1321
        return BAD_FUNC_ARG;
1322
1323
    ssl->options.dtlsSctp = 1;
1324
    return WOLFSSL_SUCCESS;
1325
}
1326
1327
#endif /* WOLFSSL_DTLS && WOLFSSL_SCTP */
1328
1329
#if (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)) && \
1330
                                                           defined(WOLFSSL_DTLS)
1331
1332
int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, word16 newMtu)
1333
{
1334
    if (ctx == NULL || newMtu > MAX_RECORD_SIZE)
1335
        return BAD_FUNC_ARG;
1336
1337
    ctx->dtlsMtuSz = newMtu;
1338
    return WOLFSSL_SUCCESS;
1339
}
1340
1341
1342
int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu)
1343
{
1344
    if (ssl == NULL)
1345
        return BAD_FUNC_ARG;
1346
1347
    if (newMtu > MAX_RECORD_SIZE) {
1348
        ssl->error = BAD_FUNC_ARG;
1349
        return WOLFSSL_FAILURE;
1350
    }
1351
1352
    ssl->dtlsMtuSz = newMtu;
1353
    return WOLFSSL_SUCCESS;
1354
}
1355
1356
#endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */
1357
1358
#ifdef WOLFSSL_SRTP
1359
1360
static const WOLFSSL_SRTP_PROTECTION_PROFILE gSrtpProfiles[] = {
1361
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 80-bits
1362
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
1363
    {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80, (((128 + 112) * 2) / 8) },
1364
    /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 32-bits
1365
     * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */
1366
    {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32, (((128 + 112) * 2) / 8) },
1367
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 80-bits */
1368
    {"SRTP_NULL_SHA1_80", SRTP_NULL_SHA1_80, ((112 * 2) / 8)},
1369
    /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 32-bits */
1370
    {"SRTP_NULL_SHA1_32", SRTP_NULL_SHA1_32, ((112 * 2) / 8)},
1371
    /* AES GCM 128, Salt: 96-bits, Auth GCM Tag 128-bits
1372
     * (master_key:128bits + master_salt:96bits) * 2 = 448 bits (56) */
1373
    {"SRTP_AEAD_AES_128_GCM", SRTP_AEAD_AES_128_GCM, (((128 + 96) * 2) / 8) },
1374
    /* AES GCM 256, Salt: 96-bits, Auth GCM Tag 128-bits
1375
     * (master_key:256bits + master_salt:96bits) * 2 = 704 bits (88) */
1376
    {"SRTP_AEAD_AES_256_GCM", SRTP_AEAD_AES_256_GCM, (((256 + 96) * 2) / 8) },
1377
};
1378
1379
static const WOLFSSL_SRTP_PROTECTION_PROFILE* DtlsSrtpFindProfile(
1380
    const char* profile_str, word32 profile_str_len, unsigned long id)
1381
{
1382
    int i;
1383
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1384
    for (i=0;
1385
         i<(int)(sizeof(gSrtpProfiles)/sizeof(WOLFSSL_SRTP_PROTECTION_PROFILE));
1386
         i++) {
1387
        if (profile_str != NULL) {
1388
            word32 srtp_profile_len = (word32)XSTRLEN(gSrtpProfiles[i].name);
1389
            if (srtp_profile_len == profile_str_len &&
1390
                XMEMCMP(gSrtpProfiles[i].name, profile_str, profile_str_len)
1391
                                                                         == 0) {
1392
                profile = &gSrtpProfiles[i];
1393
                break;
1394
            }
1395
        }
1396
        else if (id != 0 && gSrtpProfiles[i].id == id) {
1397
            profile = &gSrtpProfiles[i];
1398
            break;
1399
        }
1400
    }
1401
    return profile;
1402
}
1403
1404
/* profile_str: accepts ":" colon separated list of SRTP profiles */
1405
static int DtlsSrtpSelProfiles(word16* id, const char* profile_str)
1406
{
1407
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile;
1408
    const char *current, *next = NULL;
1409
    word32 length = 0, current_length;
1410
1411
    *id = 0; /* reset destination ID's */
1412
1413
    if (profile_str == NULL) {
1414
        return WOLFSSL_FAILURE;
1415
    }
1416
1417
    /* loop on end of line or colon ":" */
1418
    next = profile_str;
1419
    length = (word32)XSTRLEN(profile_str);
1420
    do {
1421
        current = next;
1422
        next = XSTRSTR(current, ":");
1423
        current_length = (!next) ? (word32)XSTRLEN(current)
1424
                                 : (word32)(next - current);
1425
        if (current_length < length)
1426
            length = current_length;
1427
        profile = DtlsSrtpFindProfile(current, current_length, 0);
1428
        if (profile != NULL) {
1429
            *id |= (1 << profile->id); /* selected bit based on ID */
1430
        }
1431
    } while (next != NULL && next++); /* ++ needed to skip ':' */
1432
    return WOLFSSL_SUCCESS;
1433
}
1434
1435
int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str)
1436
{
1437
    int ret = WOLFSSL_FAILURE;
1438
    if (ctx != NULL) {
1439
        ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str);
1440
    }
1441
    return ret;
1442
}
1443
int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str)
1444
{
1445
    int ret = WOLFSSL_FAILURE;
1446
    if (ssl != NULL) {
1447
        ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str);
1448
    }
1449
    return ret;
1450
}
1451
1452
const WOLFSSL_SRTP_PROTECTION_PROFILE* wolfSSL_get_selected_srtp_profile(
1453
    WOLFSSL* ssl)
1454
{
1455
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1456
    if (ssl) {
1457
        profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
1458
    }
1459
    return profile;
1460
}
1461
#ifndef NO_WOLFSSL_STUB
1462
WOLF_STACK_OF(WOLFSSL_SRTP_PROTECTION_PROFILE)* wolfSSL_get_srtp_profiles(
1463
    WOLFSSL* ssl)
1464
{
1465
    /* Not yet implemented - should return list of available SRTP profiles
1466
     * ssl->dtlsSrtpProfiles */
1467
    (void)ssl;
1468
    return NULL;
1469
}
1470
#endif
1471
1472
int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl,
1473
    unsigned char* out, size_t* olen)
1474
{
1475
    int ret = WOLFSSL_FAILURE;
1476
    const char* label = "EXTRACTOR-dtls_srtp";
1477
    const WOLFSSL_SRTP_PROTECTION_PROFILE* profile = NULL;
1478
    byte seed[SEED_LEN];
1479
1480
    if (ssl == NULL || olen == NULL) {
1481
        return BAD_FUNC_ARG;
1482
    }
1483
1484
    profile = DtlsSrtpFindProfile(NULL, 0, ssl->dtlsSrtpId);
1485
    if (profile == NULL) {
1486
        WOLFSSL_MSG("Not using DTLS SRTP");
1487
        return EXT_MISSING;
1488
    }
1489
    if (out == NULL) {
1490
        *olen = profile->kdfBits;
1491
        return LENGTH_ONLY_E;
1492
    }
1493
1494
    if (*olen < (size_t)profile->kdfBits) {
1495
        return BUFFER_E;
1496
    }
1497
1498
#ifdef WOLFSSL_HAVE_PRF
1499
    XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
1500
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
1501
1502
    PRIVATE_KEY_UNLOCK();
1503
    ret = wc_PRF_TLS(out, profile->kdfBits,   /* out: generated keys / salt */
1504
        ssl->arrays->masterSecret, SECRET_LEN,  /* existing master secret */
1505
        (const byte*)label, (int)XSTRLEN(label),/* label */
1506
        seed, SEED_LEN,                         /* seed: client/server random */
1507
        IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
1508
        ssl->heap, INVALID_DEVID);
1509
    if (ret == 0) {
1510
        *olen = profile->kdfBits;
1511
        ret = WOLFSSL_SUCCESS;
1512
    }
1513
    PRIVATE_KEY_LOCK();
1514
#else
1515
    /* Pseudo random function must be enabled in the configuration */
1516
    ret = PRF_MISSING;
1517
#endif
1518
1519
    return ret;
1520
}
1521
1522
#endif /* WOLFSSL_SRTP */
1523
1524
1525
#ifdef WOLFSSL_DTLS_DROP_STATS
1526
1527
int wolfSSL_dtls_get_drop_stats(WOLFSSL* ssl,
1528
                                word32* macDropCount, word32* replayDropCount)
1529
{
1530
    int ret;
1531
1532
    WOLFSSL_ENTER("wolfSSL_dtls_get_drop_stats()");
1533
1534
    if (ssl == NULL)
1535
        ret = BAD_FUNC_ARG;
1536
    else {
1537
        ret = WOLFSSL_SUCCESS;
1538
        if (macDropCount != NULL)
1539
            *macDropCount = ssl->macDropCount;
1540
        if (replayDropCount != NULL)
1541
            *replayDropCount = ssl->replayDropCount;
1542
    }
1543
1544
    WOLFSSL_LEAVE("wolfSSL_dtls_get_drop_stats()", ret);
1545
    return ret;
1546
}
1547
1548
#endif /* WOLFSSL_DTLS_DROP_STATS */
1549
1550
1551
#if defined(WOLFSSL_MULTICAST)
1552
1553
int wolfSSL_CTX_mcast_set_member_id(WOLFSSL_CTX* ctx, word16 id)
1554
{
1555
    int ret = 0;
1556
1557
    WOLFSSL_ENTER("wolfSSL_CTX_mcast_set_member_id()");
1558
1559
    if (ctx == NULL || id > 255)
1560
        ret = BAD_FUNC_ARG;
1561
1562
    if (ret == 0) {
1563
        ctx->haveEMS = 0;
1564
        ctx->haveMcast = 1;
1565
        ctx->mcastID = (byte)id;
1566
#ifndef WOLFSSL_USER_IO
1567
        ctx->CBIORecv = EmbedReceiveFromMcast;
1568
#endif /* WOLFSSL_USER_IO */
1569
1570
        ret = WOLFSSL_SUCCESS;
1571
    }
1572
    WOLFSSL_LEAVE("wolfSSL_CTX_mcast_set_member_id()", ret);
1573
    return ret;
1574
}
1575
1576
int wolfSSL_mcast_get_max_peers(void)
1577
{
1578
    return WOLFSSL_MULTICAST_PEERS;
1579
}
1580
1581
#ifdef WOLFSSL_DTLS
1582
static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
1583
                                         word32 second, word32 high)
1584
{
1585
    word32 newCur = 0;
1586
1587
    if (cur < first)
1588
        newCur = first;
1589
    else if (cur < second)
1590
        newCur = second;
1591
    else if (cur < high)
1592
        newCur = high;
1593
1594
    return newCur;
1595
}
1596
#endif /* WOLFSSL_DTLS */
1597
1598
1599
int wolfSSL_set_secret(WOLFSSL* ssl, word16 epoch,
1600
                       const byte* preMasterSecret, word32 preMasterSz,
1601
                       const byte* clientRandom, const byte* serverRandom,
1602
                       const byte* suite)
1603
{
1604
    int ret = 0;
1605
1606
    WOLFSSL_ENTER("wolfSSL_set_secret()");
1607
1608
    if (ssl == NULL || preMasterSecret == NULL ||
1609
        preMasterSz == 0 || preMasterSz > ENCRYPT_LEN ||
1610
        clientRandom == NULL || serverRandom == NULL || suite == NULL) {
1611
1612
        ret = BAD_FUNC_ARG;
1613
    }
1614
1615
    if (ret == 0 && ssl->arrays->preMasterSecret == NULL) {
1616
        ssl->arrays->preMasterSz = ENCRYPT_LEN;
1617
        ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
1618
            DYNAMIC_TYPE_SECRET);
1619
        if (ssl->arrays->preMasterSecret == NULL) {
1620
            ret = MEMORY_E;
1621
        }
1622
    }
1623
1624
    if (ret == 0) {
1625
        XMEMCPY(ssl->arrays->preMasterSecret, preMasterSecret, preMasterSz);
1626
        XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0, ENCRYPT_LEN - preMasterSz);
1627
        ssl->arrays->preMasterSz = preMasterSz;
1628
        XMEMCPY(ssl->arrays->clientRandom, clientRandom, RAN_LEN);
1629
        XMEMCPY(ssl->arrays->serverRandom, serverRandom, RAN_LEN);
1630
        ssl->options.cipherSuite0 = suite[0];
1631
        ssl->options.cipherSuite = suite[1];
1632
1633
        ret = SetCipherSpecs(ssl);
1634
    }
1635
1636
    if (ret == 0)
1637
        ret = MakeTlsMasterSecret(ssl);
1638
1639
    if (ret == 0) {
1640
        ssl->keys.encryptionOn = 1;
1641
        ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
1642
    }
1643
1644
    if (ret == 0) {
1645
        if (ssl->options.dtls) {
1646
        #ifdef WOLFSSL_DTLS
1647
            WOLFSSL_DTLS_PEERSEQ* peerSeq;
1648
            int i;
1649
1650
            ssl->keys.dtls_epoch = epoch;
1651
            for (i = 0, peerSeq = ssl->keys.peerSeq;
1652
                 i < WOLFSSL_DTLS_PEERSEQ_SZ;
1653
                 i++, peerSeq++) {
1654
1655
                peerSeq->nextEpoch = epoch;
1656
                peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
1657
                peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
1658
                peerSeq->nextSeq_lo = 0;
1659
                peerSeq->nextSeq_hi = 0;
1660
                XMEMCPY(peerSeq->prevWindow, peerSeq->window, DTLS_SEQ_SZ);
1661
                XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
1662
                peerSeq->highwaterMark = UpdateHighwaterMark(0,
1663
                        ssl->ctx->mcastFirstSeq,
1664
                        ssl->ctx->mcastSecondSeq,
1665
                        ssl->ctx->mcastMaxSeq);
1666
            }
1667
        #else
1668
            (void)epoch;
1669
        #endif
1670
        }
1671
        FreeHandshakeResources(ssl);
1672
        ret = WOLFSSL_SUCCESS;
1673
    }
1674
    else {
1675
        if (ssl)
1676
            ssl->error = ret;
1677
        ret = WOLFSSL_FATAL_ERROR;
1678
    }
1679
    WOLFSSL_LEAVE("wolfSSL_set_secret()", ret);
1680
    return ret;
1681
}
1682
1683
1684
#ifdef WOLFSSL_DTLS
1685
1686
int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub)
1687
{
1688
    WOLFSSL_DTLS_PEERSEQ* p = NULL;
1689
    int ret = WOLFSSL_SUCCESS;
1690
    int i;
1691
1692
    WOLFSSL_ENTER("wolfSSL_mcast_peer_add()");
1693
    if (ssl == NULL || peerId > 255)
1694
        return BAD_FUNC_ARG;
1695
1696
    if (!sub) {
1697
        /* Make sure it isn't already present, while keeping the first
1698
         * open spot. */
1699
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
1700
            if (ssl->keys.peerSeq[i].peerId == INVALID_PEER_ID)
1701
                p = &ssl->keys.peerSeq[i];
1702
            if (ssl->keys.peerSeq[i].peerId == peerId) {
1703
                WOLFSSL_MSG("Peer ID already in multicast peer list.");
1704
                p = NULL;
1705
            }
1706
        }
1707
1708
        if (p != NULL) {
1709
            XMEMSET(p, 0, sizeof(WOLFSSL_DTLS_PEERSEQ));
1710
            p->peerId = peerId;
1711
            p->highwaterMark = UpdateHighwaterMark(0,
1712
                ssl->ctx->mcastFirstSeq,
1713
                ssl->ctx->mcastSecondSeq,
1714
                ssl->ctx->mcastMaxSeq);
1715
        }
1716
        else {
1717
            WOLFSSL_MSG("No room in peer list.");
1718
            ret = -1;
1719
        }
1720
    }
1721
    else {
1722
        for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
1723
            if (ssl->keys.peerSeq[i].peerId == peerId)
1724
                p = &ssl->keys.peerSeq[i];
1725
        }
1726
1727
        if (p != NULL) {
1728
            p->peerId = INVALID_PEER_ID;
1729
        }
1730
        else {
1731
            WOLFSSL_MSG("Peer not found in list.");
1732
        }
1733
    }
1734
1735
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_add()", ret);
1736
    return ret;
1737
}
1738
1739
1740
/* If peerId is in the list of peers and its last sequence number is non-zero,
1741
 * return 1, otherwise return 0. */
1742
int wolfSSL_mcast_peer_known(WOLFSSL* ssl, unsigned short peerId)
1743
{
1744
    int known = 0;
1745
    int i;
1746
1747
    WOLFSSL_ENTER("wolfSSL_mcast_peer_known()");
1748
1749
    if (ssl == NULL || peerId > 255) {
1750
        return BAD_FUNC_ARG;
1751
    }
1752
1753
    for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++) {
1754
        if (ssl->keys.peerSeq[i].peerId == peerId) {
1755
            if (ssl->keys.peerSeq[i].nextSeq_hi ||
1756
                ssl->keys.peerSeq[i].nextSeq_lo) {
1757
1758
                known = 1;
1759
            }
1760
            break;
1761
        }
1762
    }
1763
1764
    WOLFSSL_LEAVE("wolfSSL_mcast_peer_known()", known);
1765
    return known;
1766
}
1767
1768
1769
int wolfSSL_CTX_mcast_set_highwater_cb(WOLFSSL_CTX* ctx, word32 maxSeq,
1770
                                       word32 first, word32 second,
1771
                                       CallbackMcastHighwater cb)
1772
{
1773
    if (ctx == NULL || (second && first > second) ||
1774
        first > maxSeq || second > maxSeq || cb == NULL) {
1775
1776
        return BAD_FUNC_ARG;
1777
    }
1778
1779
    ctx->mcastHwCb = cb;
1780
    ctx->mcastFirstSeq = first;
1781
    ctx->mcastSecondSeq = second;
1782
    ctx->mcastMaxSeq = maxSeq;
1783
1784
    return WOLFSSL_SUCCESS;
1785
}
1786
1787
1788
int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx)
1789
{
1790
    if (ssl == NULL || ctx == NULL)
1791
        return BAD_FUNC_ARG;
1792
1793
    ssl->mcastHwCbCtx = ctx;
1794
1795
    return WOLFSSL_SUCCESS;
1796
}
1797
1798
#endif /* WOLFSSL_DTLS */
1799
1800
#endif /* WOLFSSL_MULTICAST */
1801
1802
1803
#endif /* WOLFSSL_LEANPSK */
1804
1805
1806
/* return underlying connect or accept, WOLFSSL_SUCCESS on ok */
1807
int wolfSSL_negotiate(WOLFSSL* ssl)
1808
0
{
1809
0
    int err = WOLFSSL_FATAL_ERROR;
1810
1811
0
    WOLFSSL_ENTER("wolfSSL_negotiate");
1812
1813
0
    if (ssl == NULL)
1814
0
        return WOLFSSL_FATAL_ERROR;
1815
1816
0
#ifndef NO_WOLFSSL_SERVER
1817
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1818
0
#ifdef WOLFSSL_TLS13
1819
0
        if (IsAtLeastTLSv1_3(ssl->version))
1820
0
            err = wolfSSL_accept_TLSv13(ssl);
1821
0
        else
1822
0
#endif
1823
0
            err = wolfSSL_accept(ssl);
1824
0
    }
1825
0
#endif
1826
1827
0
#ifndef NO_WOLFSSL_CLIENT
1828
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1829
0
#ifdef WOLFSSL_TLS13
1830
0
        if (IsAtLeastTLSv1_3(ssl->version))
1831
0
            err = wolfSSL_connect_TLSv13(ssl);
1832
0
        else
1833
0
#endif
1834
0
            err = wolfSSL_connect(ssl);
1835
0
    }
1836
0
#endif
1837
1838
0
    (void)ssl;
1839
1840
0
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
1841
1842
0
    return err;
1843
0
}
1844
1845
1846
WOLFSSL_ABI
1847
WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
1848
0
{
1849
0
    if (ssl) {
1850
0
        return ssl->rng;
1851
0
    }
1852
1853
0
    return NULL;
1854
0
}
1855
1856
1857
#ifndef WOLFSSL_LEANPSK
1858
/* object size based on build */
1859
int wolfSSL_GetObjectSize(void)
1860
0
{
1861
#ifdef SHOW_SIZES
1862
    printf("sizeof suites           = %lu\n", (unsigned long)sizeof(Suites));
1863
    printf("sizeof ciphers(2)       = %lu\n", (unsigned long)sizeof(Ciphers));
1864
#ifndef NO_RC4
1865
    printf("\tsizeof arc4         = %lu\n", (unsigned long)sizeof(Arc4));
1866
#endif
1867
    printf("\tsizeof aes          = %lu\n", (unsigned long)sizeof(Aes));
1868
#ifndef NO_DES3
1869
    printf("\tsizeof des3         = %lu\n", (unsigned long)sizeof(Des3));
1870
#endif
1871
#ifdef HAVE_CHACHA
1872
    printf("\tsizeof chacha       = %lu\n", (unsigned long)sizeof(ChaCha));
1873
#endif
1874
    printf("sizeof cipher specs     = %lu\n", (unsigned long)sizeof(CipherSpecs));
1875
    printf("sizeof keys             = %lu\n", (unsigned long)sizeof(Keys));
1876
    printf("sizeof Hashes(2)        = %lu\n", (unsigned long)sizeof(Hashes));
1877
#ifndef NO_MD5
1878
    printf("\tsizeof MD5          = %lu\n", (unsigned long)sizeof(wc_Md5));
1879
#endif
1880
#ifndef NO_SHA
1881
    printf("\tsizeof SHA          = %lu\n", (unsigned long)sizeof(wc_Sha));
1882
#endif
1883
#ifdef WOLFSSL_SHA224
1884
    printf("\tsizeof SHA224       = %lu\n", (unsigned long)sizeof(wc_Sha224));
1885
#endif
1886
#ifndef NO_SHA256
1887
    printf("\tsizeof SHA256       = %lu\n", (unsigned long)sizeof(wc_Sha256));
1888
#endif
1889
#ifdef WOLFSSL_SHA384
1890
    printf("\tsizeof SHA384       = %lu\n", (unsigned long)sizeof(wc_Sha384));
1891
#endif
1892
#ifdef WOLFSSL_SHA384
1893
    printf("\tsizeof SHA512       = %lu\n", (unsigned long)sizeof(wc_Sha512));
1894
#endif
1895
    printf("sizeof Buffers          = %lu\n", (unsigned long)sizeof(Buffers));
1896
    printf("sizeof Options          = %lu\n", (unsigned long)sizeof(Options));
1897
    printf("sizeof Arrays           = %lu\n", (unsigned long)sizeof(Arrays));
1898
#ifndef NO_RSA
1899
    printf("sizeof RsaKey           = %lu\n", (unsigned long)sizeof(RsaKey));
1900
#endif
1901
#ifdef HAVE_ECC
1902
    printf("sizeof ecc_key          = %lu\n", (unsigned long)sizeof(ecc_key));
1903
#endif
1904
    printf("sizeof WOLFSSL_CIPHER    = %lu\n", (unsigned long)sizeof(WOLFSSL_CIPHER));
1905
    printf("sizeof WOLFSSL_SESSION   = %lu\n", (unsigned long)sizeof(WOLFSSL_SESSION));
1906
    printf("sizeof WOLFSSL           = %lu\n", (unsigned long)sizeof(WOLFSSL));
1907
    printf("sizeof WOLFSSL_CTX       = %lu\n", (unsigned long)sizeof(WOLFSSL_CTX));
1908
#endif
1909
1910
0
    return sizeof(WOLFSSL);
1911
0
}
1912
1913
int wolfSSL_CTX_GetObjectSize(void)
1914
0
{
1915
0
    return sizeof(WOLFSSL_CTX);
1916
0
}
1917
1918
int wolfSSL_METHOD_GetObjectSize(void)
1919
0
{
1920
0
    return sizeof(WOLFSSL_METHOD);
1921
0
}
1922
#endif
1923
1924
1925
#ifdef WOLFSSL_STATIC_MEMORY
1926
1927
int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, wolfSSL_method_func method,
1928
                                   unsigned char* buf, unsigned int sz,
1929
                                   int flag, int maxSz)
1930
{
1931
    WOLFSSL_HEAP*      heap;
1932
    WOLFSSL_HEAP_HINT* hint;
1933
    word32 idx = 0;
1934
1935
    if (ctx == NULL || buf == NULL) {
1936
        return BAD_FUNC_ARG;
1937
    }
1938
1939
    if (*ctx == NULL && method == NULL) {
1940
        return BAD_FUNC_ARG;
1941
    }
1942
1943
    if (*ctx == NULL || (*ctx)->heap == NULL) {
1944
        if (sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT) > sz - idx) {
1945
            return BUFFER_E; /* not enough memory for structures */
1946
        }
1947
        heap = (WOLFSSL_HEAP*)buf;
1948
        idx += sizeof(WOLFSSL_HEAP);
1949
        if (wolfSSL_init_memory_heap(heap) != 0) {
1950
            return WOLFSSL_FAILURE;
1951
        }
1952
        hint = (WOLFSSL_HEAP_HINT*)(buf + idx);
1953
        idx += sizeof(WOLFSSL_HEAP_HINT);
1954
        XMEMSET(hint, 0, sizeof(WOLFSSL_HEAP_HINT));
1955
        hint->memory = heap;
1956
1957
        if (*ctx && (*ctx)->heap == NULL) {
1958
            (*ctx)->heap = (void*)hint;
1959
        }
1960
    }
1961
    else {
1962
#ifdef WOLFSSL_HEAP_TEST
1963
        /* do not load in memory if test has been set */
1964
        if ((*ctx)->heap == (void*)WOLFSSL_HEAP_TEST) {
1965
            return WOLFSSL_SUCCESS;
1966
        }
1967
#endif
1968
        hint = (WOLFSSL_HEAP_HINT*)((*ctx)->heap);
1969
        heap = hint->memory;
1970
    }
1971
1972
    if (wolfSSL_load_static_memory(buf + idx, sz - idx, flag, heap) != 1) {
1973
        WOLFSSL_MSG("Error partitioning memory");
1974
        return WOLFSSL_FAILURE;
1975
    }
1976
1977
    /* create ctx if needed */
1978
    if (*ctx == NULL) {
1979
        *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
1980
        if (*ctx == NULL) {
1981
            WOLFSSL_MSG("Error creating ctx");
1982
            return WOLFSSL_FAILURE;
1983
        }
1984
    }
1985
1986
    /* determine what max applies too */
1987
    if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
1988
        heap->maxIO = maxSz;
1989
    }
1990
    else { /* general memory used in handshakes */
1991
        heap->maxHa = maxSz;
1992
    }
1993
1994
    heap->flag |= flag;
1995
1996
    (void)maxSz;
1997
    (void)method;
1998
1999
    return WOLFSSL_SUCCESS;
2000
}
2001
2002
2003
int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
2004
{
2005
    if (ssl == NULL) {
2006
        return BAD_FUNC_ARG;
2007
    }
2008
    WOLFSSL_ENTER("wolfSSL_is_static_memory");
2009
2010
    /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
2011
    if (mem_stats != NULL && ssl->heap != NULL) {
2012
        WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
2013
        WOLFSSL_HEAP* heap      = hint->memory;
2014
        if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
2015
            XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
2016
        }
2017
    }
2018
2019
    return (ssl->heap) ? 1 : 0;
2020
}
2021
2022
2023
int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
2024
{
2025
    if (ctx == NULL) {
2026
        return BAD_FUNC_ARG;
2027
    }
2028
    WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
2029
2030
    /* fill out statistics if wanted */
2031
    if (mem_stats != NULL && ctx->heap != NULL) {
2032
        WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
2033
        if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
2034
            return MEMORY_E;
2035
        }
2036
    }
2037
2038
    return (ctx->heap) ? 1 : 0;
2039
}
2040
2041
#endif /* WOLFSSL_STATIC_MEMORY */
2042
2043
2044
/* return max record layer size plaintext input size */
2045
int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
2046
0
{
2047
0
    WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
2048
2049
0
    if (ssl == NULL)
2050
0
        return BAD_FUNC_ARG;
2051
2052
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE) {
2053
0
        WOLFSSL_MSG("Handshake not complete yet");
2054
0
        return BAD_FUNC_ARG;
2055
0
    }
2056
2057
0
    return wolfSSL_GetMaxFragSize(ssl, OUTPUT_RECORD_SIZE);
2058
0
}
2059
2060
2061
/* return record layer size of plaintext input size */
2062
int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
2063
0
{
2064
0
    int maxSize;
2065
2066
0
    WOLFSSL_ENTER("wolfSSL_GetOutputSize");
2067
2068
0
    if (inSz < 0)
2069
0
        return BAD_FUNC_ARG;
2070
2071
0
    maxSize = wolfSSL_GetMaxOutputSize(ssl);
2072
0
    if (maxSize < 0)
2073
0
        return maxSize;   /* error */
2074
0
    if (inSz > maxSize)
2075
0
        return INPUT_SIZE_E;
2076
2077
0
    return BuildMessage(ssl, NULL, 0, NULL, inSz, application_data, 0, 1, 0, CUR_ORDER);
2078
0
}
2079
2080
2081
#ifdef HAVE_ECC
2082
int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2083
0
{
2084
0
    if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
2085
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
2086
0
        return BAD_FUNC_ARG;
2087
0
    }
2088
2089
0
    ctx->minEccKeySz     = keySz / 8;
2090
0
#ifndef NO_CERTS
2091
0
    ctx->cm->minEccKeySz = keySz / 8;
2092
0
#endif
2093
0
    return WOLFSSL_SUCCESS;
2094
0
}
2095
2096
2097
int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz)
2098
0
{
2099
0
    if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
2100
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
2101
0
        return BAD_FUNC_ARG;
2102
0
    }
2103
2104
0
    ssl->options.minEccKeySz = keySz / 8;
2105
0
    return WOLFSSL_SUCCESS;
2106
0
}
2107
2108
#endif /* HAVE_ECC */
2109
2110
#ifndef NO_RSA
2111
int wolfSSL_CTX_SetMinRsaKey_Sz(WOLFSSL_CTX* ctx, short keySz)
2112
0
{
2113
0
    if (ctx == NULL || keySz < 0 || keySz % 8 != 0) {
2114
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null");
2115
0
        return BAD_FUNC_ARG;
2116
0
    }
2117
2118
0
    ctx->minRsaKeySz     = keySz / 8;
2119
0
    ctx->cm->minRsaKeySz = keySz / 8;
2120
0
    return WOLFSSL_SUCCESS;
2121
0
}
2122
2123
2124
int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz)
2125
0
{
2126
0
    if (ssl == NULL || keySz < 0 || keySz % 8 != 0) {
2127
0
        WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null");
2128
0
        return BAD_FUNC_ARG;
2129
0
    }
2130
2131
0
    ssl->options.minRsaKeySz = keySz / 8;
2132
0
    return WOLFSSL_SUCCESS;
2133
0
}
2134
#endif /* !NO_RSA */
2135
2136
#ifndef NO_DH
2137
/* server Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
2138
int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz,
2139
                    const unsigned char* g, int gSz)
2140
0
{
2141
0
    WOLFSSL_ENTER("wolfSSL_SetTmpDH");
2142
2143
0
    if (ssl == NULL || p == NULL || g == NULL)
2144
0
        return BAD_FUNC_ARG;
2145
2146
0
    if ((word16)pSz < ssl->options.minDhKeySz)
2147
0
        return DH_KEY_SIZE_E;
2148
0
    if ((word16)pSz > ssl->options.maxDhKeySz)
2149
0
        return DH_KEY_SIZE_E;
2150
2151
    /* this function is for server only */
2152
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
2153
0
        return SIDE_ERROR;
2154
2155
0
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
2156
0
        !defined(HAVE_SELFTEST)
2157
0
        ssl->options.dhKeyTested = 0;
2158
0
        ssl->options.dhDoKeyTest = 1;
2159
0
    #endif
2160
2161
0
    if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
2162
0
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2163
0
        ssl->buffers.serverDH_P.buffer = NULL;
2164
0
    }
2165
0
    if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
2166
0
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2167
0
        ssl->buffers.serverDH_G.buffer = NULL;
2168
0
    }
2169
2170
0
    ssl->buffers.weOwnDH = 1;  /* SSL owns now */
2171
0
    ssl->buffers.serverDH_P.buffer = (byte*)XMALLOC(pSz, ssl->heap,
2172
0
                                                    DYNAMIC_TYPE_PUBLIC_KEY);
2173
0
    if (ssl->buffers.serverDH_P.buffer == NULL)
2174
0
            return MEMORY_E;
2175
2176
0
    ssl->buffers.serverDH_G.buffer = (byte*)XMALLOC(gSz, ssl->heap,
2177
0
                                                    DYNAMIC_TYPE_PUBLIC_KEY);
2178
0
    if (ssl->buffers.serverDH_G.buffer == NULL) {
2179
0
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2180
0
        ssl->buffers.serverDH_P.buffer = NULL;
2181
0
        return MEMORY_E;
2182
0
    }
2183
2184
0
    ssl->buffers.serverDH_P.length = pSz;
2185
0
    ssl->buffers.serverDH_G.length = gSz;
2186
2187
0
    XMEMCPY(ssl->buffers.serverDH_P.buffer, p, pSz);
2188
0
    XMEMCPY(ssl->buffers.serverDH_G.buffer, g, gSz);
2189
2190
0
    ssl->options.haveDH = 1;
2191
2192
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
2193
0
        word16 havePSK;
2194
0
        word16 haveRSA;
2195
0
        int    keySz   = 0;
2196
2197
    #ifndef NO_PSK
2198
        havePSK = ssl->options.havePSK;
2199
    #else
2200
0
        havePSK = 0;
2201
0
    #endif
2202
    #ifdef NO_RSA
2203
        haveRSA = 0;
2204
    #else
2205
0
        haveRSA = 1;
2206
0
    #endif
2207
0
    #ifndef NO_CERTS
2208
0
        keySz = ssl->buffers.keySz;
2209
0
    #endif
2210
0
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
2211
0
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
2212
0
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
2213
0
                   ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
2214
0
                   ssl->options.haveAnon, TRUE, ssl->options.side);
2215
0
    }
2216
2217
0
    WOLFSSL_LEAVE("wolfSSL_SetTmpDH", 0);
2218
2219
0
    return WOLFSSL_SUCCESS;
2220
0
}
2221
2222
2223
#if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
2224
    !defined(HAVE_SELFTEST)
2225
/* Enables or disables the session's DH key prime test. */
2226
int wolfSSL_SetEnableDhKeyTest(WOLFSSL* ssl, int enable)
2227
0
{
2228
0
    WOLFSSL_ENTER("wolfSSL_SetEnableDhKeyTest");
2229
2230
0
    if (ssl == NULL)
2231
0
        return BAD_FUNC_ARG;
2232
2233
0
    if (!enable)
2234
0
        ssl->options.dhDoKeyTest = 0;
2235
0
    else
2236
0
        ssl->options.dhDoKeyTest = 1;
2237
2238
0
    WOLFSSL_LEAVE("wolfSSL_SetEnableDhKeyTest", WOLFSSL_SUCCESS);
2239
0
    return WOLFSSL_SUCCESS;
2240
0
}
2241
#endif
2242
2243
2244
/* server ctx Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */
2245
int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz,
2246
                         const unsigned char* g, int gSz)
2247
0
{
2248
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetTmpDH");
2249
0
    if (ctx == NULL || p == NULL || g == NULL) return BAD_FUNC_ARG;
2250
2251
0
    if ((word16)pSz < ctx->minDhKeySz)
2252
0
        return DH_KEY_SIZE_E;
2253
0
    if ((word16)pSz > ctx->maxDhKeySz)
2254
0
        return DH_KEY_SIZE_E;
2255
2256
0
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
2257
0
        !defined(HAVE_SELFTEST)
2258
0
    {
2259
0
        WC_RNG rng;
2260
0
        int error, freeKey = 0;
2261
0
    #ifdef WOLFSSL_SMALL_STACK
2262
0
        DhKey *checkKey = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
2263
0
        if (checkKey == NULL)
2264
0
            return MEMORY_E;
2265
    #else
2266
        DhKey checkKey[1];
2267
    #endif
2268
2269
0
        error = wc_InitRng(&rng);
2270
0
        if (!error)
2271
0
            error = wc_InitDhKey(checkKey);
2272
0
        if (!error) {
2273
0
            freeKey = 1;
2274
0
            error = wc_DhSetCheckKey(checkKey,
2275
0
                                 p, pSz, g, gSz, NULL, 0, 0, &rng);
2276
0
        }
2277
0
        if (freeKey)
2278
0
            wc_FreeDhKey(checkKey);
2279
0
    #ifdef WOLFSSL_SMALL_STACK
2280
0
        XFREE(checkKey, NULL, DYNAMIC_TYPE_DH);
2281
0
    #endif
2282
0
        wc_FreeRng(&rng);
2283
0
        if (error)
2284
0
            return error;
2285
2286
0
        ctx->dhKeyTested = 1;
2287
0
    }
2288
0
    #endif
2289
2290
0
    XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2291
0
    ctx->serverDH_P.buffer = NULL;
2292
0
    XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2293
0
    ctx->serverDH_G.buffer = NULL;
2294
2295
0
    ctx->serverDH_P.buffer = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2296
0
    if (ctx->serverDH_P.buffer == NULL)
2297
0
       return MEMORY_E;
2298
2299
0
    ctx->serverDH_G.buffer = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2300
0
    if (ctx->serverDH_G.buffer == NULL) {
2301
0
        XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
2302
0
        ctx->serverDH_P.buffer = NULL;
2303
0
        return MEMORY_E;
2304
0
    }
2305
2306
0
    ctx->serverDH_P.length = pSz;
2307
0
    ctx->serverDH_G.length = gSz;
2308
2309
0
    XMEMCPY(ctx->serverDH_P.buffer, p, pSz);
2310
0
    XMEMCPY(ctx->serverDH_G.buffer, g, gSz);
2311
2312
0
    ctx->haveDH = 1;
2313
2314
0
    WOLFSSL_LEAVE("wolfSSL_CTX_SetTmpDH", 0);
2315
0
    return WOLFSSL_SUCCESS;
2316
0
}
2317
2318
2319
int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
2320
0
{
2321
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2322
0
        return BAD_FUNC_ARG;
2323
2324
0
    ctx->minDhKeySz = keySz_bits / 8;
2325
0
    return WOLFSSL_SUCCESS;
2326
0
}
2327
2328
2329
int wolfSSL_SetMinDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
2330
0
{
2331
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2332
0
        return BAD_FUNC_ARG;
2333
2334
0
    ssl->options.minDhKeySz = keySz_bits / 8;
2335
0
    return WOLFSSL_SUCCESS;
2336
0
}
2337
2338
2339
int wolfSSL_CTX_SetMaxDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits)
2340
0
{
2341
0
    if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2342
0
        return BAD_FUNC_ARG;
2343
2344
0
    ctx->maxDhKeySz = keySz_bits / 8;
2345
0
    return WOLFSSL_SUCCESS;
2346
0
}
2347
2348
2349
int wolfSSL_SetMaxDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits)
2350
0
{
2351
0
    if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0)
2352
0
        return BAD_FUNC_ARG;
2353
2354
0
    ssl->options.maxDhKeySz = keySz_bits / 8;
2355
0
    return WOLFSSL_SUCCESS;
2356
0
}
2357
2358
2359
int wolfSSL_GetDhKey_Sz(WOLFSSL* ssl)
2360
0
{
2361
0
    if (ssl == NULL)
2362
0
        return BAD_FUNC_ARG;
2363
2364
0
    return (ssl->options.dhKeySz * 8);
2365
0
}
2366
2367
#endif /* !NO_DH */
2368
2369
2370
WOLFSSL_ABI
2371
int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz)
2372
0
{
2373
0
    int ret;
2374
2375
0
    WOLFSSL_ENTER("SSL_write()");
2376
2377
0
    if (ssl == NULL || data == NULL || sz < 0)
2378
0
        return BAD_FUNC_ARG;
2379
2380
#ifdef WOLFSSL_QUIC
2381
    if (WOLFSSL_IS_QUIC(ssl)) {
2382
        WOLFSSL_MSG("SSL_write() on QUIC not allowed");
2383
        return BAD_FUNC_ARG;
2384
    }
2385
#endif
2386
#ifdef WOLFSSL_EARLY_DATA
2387
    if (ssl->earlyData != no_early_data && (ret = wolfSSL_negotiate(ssl)) < 0) {
2388
        ssl->error = ret;
2389
        return WOLFSSL_FATAL_ERROR;
2390
    }
2391
    ssl->earlyData = no_early_data;
2392
#endif
2393
2394
#ifdef HAVE_WRITE_DUP
2395
    { /* local variable scope */
2396
        int dupErr = 0;   /* local copy */
2397
2398
        ret = 0;
2399
2400
        if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
2401
            WOLFSSL_MSG("Read dup side cannot write");
2402
            return WRITE_DUP_WRITE_E;
2403
        }
2404
        if (ssl->dupWrite) {
2405
            if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0) {
2406
                return BAD_MUTEX_E;
2407
            }
2408
            dupErr = ssl->dupWrite->dupErr;
2409
            ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
2410
        }
2411
2412
        if (ret != 0) {
2413
            ssl->error = ret;  /* high priority fatal error */
2414
            return WOLFSSL_FATAL_ERROR;
2415
        }
2416
        if (dupErr != 0) {
2417
            WOLFSSL_MSG("Write dup error from other side");
2418
            ssl->error = dupErr;
2419
            return WOLFSSL_FATAL_ERROR;
2420
        }
2421
    }
2422
#endif
2423
2424
0
#ifdef HAVE_ERRNO_H
2425
0
    errno = 0;
2426
0
#endif
2427
2428
    #ifdef OPENSSL_EXTRA
2429
    if (ssl->CBIS != NULL) {
2430
        ssl->CBIS(ssl, SSL_CB_WRITE, WOLFSSL_SUCCESS);
2431
        ssl->cbmode = SSL_CB_WRITE;
2432
    }
2433
    #endif
2434
0
    ret = SendData(ssl, data, sz);
2435
2436
0
    WOLFSSL_LEAVE("SSL_write()", ret);
2437
2438
0
    if (ret < 0)
2439
0
        return WOLFSSL_FATAL_ERROR;
2440
0
    else
2441
0
        return ret;
2442
0
}
2443
2444
static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek)
2445
0
{
2446
0
    int ret;
2447
2448
0
    WOLFSSL_ENTER("wolfSSL_read_internal()");
2449
2450
0
    if (ssl == NULL || data == NULL || sz < 0)
2451
0
        return BAD_FUNC_ARG;
2452
2453
#ifdef WOLFSSL_QUIC
2454
    if (WOLFSSL_IS_QUIC(ssl)) {
2455
        WOLFSSL_MSG("SSL_read() on QUIC not allowed");
2456
        return BAD_FUNC_ARG;
2457
    }
2458
#endif
2459
#if defined(WOLFSSL_ERROR_CODE_OPENSSL) && defined(OPENSSL_EXTRA)
2460
    /* This additional logic is meant to simulate following openSSL behavior:
2461
     * After bidirectional SSL_shutdown complete, SSL_read returns 0 and
2462
     * SSL_get_error_code returns SSL_ERROR_ZERO_RETURN.
2463
     * This behavior is used to know the disconnect of the underlying
2464
     * transport layer.
2465
     *
2466
     * In this logic, CBIORecv is called with a read size of 0 to check the
2467
     * transport layer status. It also returns WOLFSSL_FAILURE so that
2468
     * SSL_read does not return a positive number on failure.
2469
     */
2470
2471
    /* make sure bidirectional TLS shutdown completes */
2472
    if (ssl->error == WOLFSSL_ERROR_SYSCALL) {
2473
        /* ask the underlying transport the connection is closed */
2474
        if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx) ==
2475
                                            WOLFSSL_CBIO_ERR_CONN_CLOSE) {
2476
            ssl->options.isClosed = 1;
2477
            ssl->error = WOLFSSL_ERROR_ZERO_RETURN;
2478
        }
2479
        return WOLFSSL_FAILURE;
2480
    }
2481
#endif
2482
2483
#ifdef HAVE_WRITE_DUP
2484
    if (ssl->dupWrite && ssl->dupSide == WRITE_DUP_SIDE) {
2485
        WOLFSSL_MSG("Write dup side cannot read");
2486
        return WRITE_DUP_READ_E;
2487
    }
2488
#endif
2489
2490
0
#ifdef HAVE_ERRNO_H
2491
0
        errno = 0;
2492
0
#endif
2493
2494
#ifdef WOLFSSL_DTLS
2495
    if (ssl->options.dtls) {
2496
        ssl->dtls_expected_rx = max(sz + DTLS_MTU_ADDITIONAL_READ_BUFFER,
2497
                MAX_MTU);
2498
#ifdef WOLFSSL_SCTP
2499
        if (ssl->options.dtlsSctp)
2500
#endif
2501
#if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
2502
            /* Add some bytes so that we can operate with slight difference
2503
             * in set MTU size on each peer */
2504
            ssl->dtls_expected_rx = max(ssl->dtls_expected_rx,
2505
                    ssl->dtlsMtuSz + (word32)DTLS_MTU_ADDITIONAL_READ_BUFFER);
2506
#endif
2507
    }
2508
#endif
2509
2510
0
    ret = ReceiveData(ssl, (byte*)data, sz, peek);
2511
2512
#ifdef HAVE_WRITE_DUP
2513
    if (ssl->dupWrite) {
2514
        if (ssl->error != 0 && ssl->error != WANT_READ
2515
        #ifdef WOLFSSL_ASYNC_CRYPT
2516
            && ssl->error != WC_PENDING_E
2517
        #endif
2518
        ) {
2519
            int notifyErr;
2520
2521
            WOLFSSL_MSG("Notifying write side of fatal read error");
2522
            notifyErr  = NotifyWriteSide(ssl, ssl->error);
2523
            if (notifyErr < 0) {
2524
                ret = ssl->error = notifyErr;
2525
            }
2526
        }
2527
    }
2528
#endif
2529
2530
0
    WOLFSSL_LEAVE("wolfSSL_read_internal()", ret);
2531
2532
0
    if (ret < 0)
2533
0
        return WOLFSSL_FATAL_ERROR;
2534
0
    else
2535
0
        return ret;
2536
0
}
2537
2538
2539
int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz)
2540
0
{
2541
0
    WOLFSSL_ENTER("wolfSSL_peek()");
2542
2543
0
    return wolfSSL_read_internal(ssl, data, sz, TRUE);
2544
0
}
2545
2546
2547
WOLFSSL_ABI
2548
int wolfSSL_read(WOLFSSL* ssl, void* data, int sz)
2549
0
{
2550
0
    WOLFSSL_ENTER("wolfSSL_read()");
2551
2552
    #ifdef OPENSSL_EXTRA
2553
    if (ssl == NULL) {
2554
        return BAD_FUNC_ARG;
2555
    }
2556
    if (ssl->CBIS != NULL) {
2557
        ssl->CBIS(ssl, SSL_CB_READ, WOLFSSL_SUCCESS);
2558
        ssl->cbmode = SSL_CB_READ;
2559
    }
2560
    #endif
2561
0
    return wolfSSL_read_internal(ssl, data, sz, FALSE);
2562
0
}
2563
2564
2565
#ifdef WOLFSSL_MULTICAST
2566
2567
int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz)
2568
{
2569
    int ret = 0;
2570
2571
    WOLFSSL_ENTER("wolfSSL_mcast_read()");
2572
2573
    if (ssl == NULL)
2574
        return BAD_FUNC_ARG;
2575
2576
    ret = wolfSSL_read_internal(ssl, data, sz, FALSE);
2577
    if (ssl->options.dtls && ssl->options.haveMcast && id != NULL)
2578
        *id = ssl->keys.curPeerId;
2579
    return ret;
2580
}
2581
2582
#endif /* WOLFSSL_MULTICAST */
2583
2584
2585
/* helpers to set the device id, WOLFSSL_SUCCESS on ok */
2586
WOLFSSL_ABI
2587
int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
2588
0
{
2589
0
    if (ssl == NULL)
2590
0
        return BAD_FUNC_ARG;
2591
2592
0
    ssl->devId = devId;
2593
2594
0
    return WOLFSSL_SUCCESS;
2595
0
}
2596
2597
WOLFSSL_ABI
2598
int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
2599
0
{
2600
0
    if (ctx == NULL)
2601
0
        return BAD_FUNC_ARG;
2602
2603
0
    ctx->devId = devId;
2604
2605
0
    return WOLFSSL_SUCCESS;
2606
0
}
2607
2608
/* helpers to get device id and heap */
2609
WOLFSSL_ABI
2610
int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
2611
0
{
2612
0
    int devId = INVALID_DEVID;
2613
0
    if (ssl != NULL)
2614
0
        devId = ssl->devId;
2615
0
    if (ctx != NULL && devId == INVALID_DEVID)
2616
0
        devId = ctx->devId;
2617
0
    return devId;
2618
0
}
2619
void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
2620
0
{
2621
0
    void* heap = NULL;
2622
0
    if (ctx != NULL)
2623
0
        heap = ctx->heap;
2624
0
    else if (ssl != NULL)
2625
0
        heap = ssl->heap;
2626
0
    return heap;
2627
0
}
2628
2629
2630
#ifdef HAVE_SNI
2631
2632
WOLFSSL_ABI
2633
int wolfSSL_UseSNI(WOLFSSL* ssl, byte type, const void* data, word16 size)
2634
{
2635
    if (ssl == NULL)
2636
        return BAD_FUNC_ARG;
2637
2638
    return TLSX_UseSNI(&ssl->extensions, type, data, size, ssl->heap);
2639
}
2640
2641
2642
WOLFSSL_ABI
2643
int wolfSSL_CTX_UseSNI(WOLFSSL_CTX* ctx, byte type, const void* data,
2644
                                                                    word16 size)
2645
{
2646
    if (ctx == NULL)
2647
        return BAD_FUNC_ARG;
2648
2649
    return TLSX_UseSNI(&ctx->extensions, type, data, size, ctx->heap);
2650
}
2651
2652
#ifndef NO_WOLFSSL_SERVER
2653
2654
void wolfSSL_SNI_SetOptions(WOLFSSL* ssl, byte type, byte options)
2655
{
2656
    if (ssl && ssl->extensions)
2657
        TLSX_SNI_SetOptions(ssl->extensions, type, options);
2658
}
2659
2660
2661
void wolfSSL_CTX_SNI_SetOptions(WOLFSSL_CTX* ctx, byte type, byte options)
2662
{
2663
    if (ctx && ctx->extensions)
2664
        TLSX_SNI_SetOptions(ctx->extensions, type, options);
2665
}
2666
2667
2668
byte wolfSSL_SNI_Status(WOLFSSL* ssl, byte type)
2669
{
2670
    return TLSX_SNI_Status(ssl ? ssl->extensions : NULL, type);
2671
}
2672
2673
2674
word16 wolfSSL_SNI_GetRequest(WOLFSSL* ssl, byte type, void** data)
2675
{
2676
    if (data)
2677
        *data = NULL;
2678
2679
    if (ssl && ssl->extensions)
2680
        return TLSX_SNI_GetRequest(ssl->extensions, type, data);
2681
2682
    return 0;
2683
}
2684
2685
2686
int wolfSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
2687
                              byte type, byte* sni, word32* inOutSz)
2688
{
2689
    if (clientHello && helloSz > 0 && sni && inOutSz && *inOutSz > 0)
2690
        return TLSX_SNI_GetFromBuffer(clientHello, helloSz, type, sni, inOutSz);
2691
2692
    return BAD_FUNC_ARG;
2693
}
2694
2695
#endif /* NO_WOLFSSL_SERVER */
2696
2697
#endif /* HAVE_SNI */
2698
2699
2700
#ifdef HAVE_TRUSTED_CA
2701
2702
WOLFSSL_API int wolfSSL_UseTrustedCA(WOLFSSL* ssl, byte type,
2703
            const byte* certId, word32 certIdSz)
2704
{
2705
    if (ssl == NULL)
2706
        return BAD_FUNC_ARG;
2707
2708
    if (type == WOLFSSL_TRUSTED_CA_PRE_AGREED) {
2709
        if (certId != NULL || certIdSz != 0)
2710
            return BAD_FUNC_ARG;
2711
    }
2712
    else if (type == WOLFSSL_TRUSTED_CA_X509_NAME) {
2713
        if (certId == NULL || certIdSz == 0)
2714
            return BAD_FUNC_ARG;
2715
    }
2716
    #ifndef NO_SHA
2717
    else if (type == WOLFSSL_TRUSTED_CA_KEY_SHA1 ||
2718
            type == WOLFSSL_TRUSTED_CA_CERT_SHA1) {
2719
        if (certId == NULL || certIdSz != WC_SHA_DIGEST_SIZE)
2720
            return BAD_FUNC_ARG;
2721
    }
2722
    #endif
2723
    else
2724
        return BAD_FUNC_ARG;
2725
2726
    return TLSX_UseTrustedCA(&ssl->extensions,
2727
            type, certId, certIdSz, ssl->heap);
2728
}
2729
2730
#endif /* HAVE_TRUSTED_CA */
2731
2732
2733
#ifdef HAVE_MAX_FRAGMENT
2734
#ifndef NO_WOLFSSL_CLIENT
2735
2736
int wolfSSL_UseMaxFragment(WOLFSSL* ssl, byte mfl)
2737
{
2738
    if (ssl == NULL)
2739
        return BAD_FUNC_ARG;
2740
2741
#ifdef WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST
2742
    /* The following is a non-standard way to reconfigure the max packet size
2743
        post-handshake for wolfSSL_write/wolfSSL_read */
2744
    if (ssl->options.handShakeState == HANDSHAKE_DONE) {
2745
        switch (mfl) {
2746
            case WOLFSSL_MFL_2_8 : ssl->max_fragment =  256; break;
2747
            case WOLFSSL_MFL_2_9 : ssl->max_fragment =  512; break;
2748
            case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
2749
            case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
2750
            case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
2751
            case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
2752
            default: ssl->max_fragment = MAX_RECORD_SIZE; break;
2753
        }
2754
        return WOLFSSL_SUCCESS;
2755
    }
2756
#endif /* WOLFSSL_MAX_FRAGMENT_ADJUST */
2757
2758
    /* This call sets the max fragment TLS extension, which gets sent to server.
2759
        The server_hello response is what sets the `ssl->max_fragment` in
2760
        TLSX_MFL_Parse */
2761
    return TLSX_UseMaxFragment(&ssl->extensions, mfl, ssl->heap);
2762
}
2763
2764
2765
int wolfSSL_CTX_UseMaxFragment(WOLFSSL_CTX* ctx, byte mfl)
2766
{
2767
    if (ctx == NULL)
2768
        return BAD_FUNC_ARG;
2769
2770
    return TLSX_UseMaxFragment(&ctx->extensions, mfl, ctx->heap);
2771
}
2772
2773
#endif /* NO_WOLFSSL_CLIENT */
2774
#endif /* HAVE_MAX_FRAGMENT */
2775
2776
#ifdef HAVE_TRUNCATED_HMAC
2777
#ifndef NO_WOLFSSL_CLIENT
2778
2779
int wolfSSL_UseTruncatedHMAC(WOLFSSL* ssl)
2780
{
2781
    if (ssl == NULL)
2782
        return BAD_FUNC_ARG;
2783
2784
    return TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
2785
}
2786
2787
2788
int wolfSSL_CTX_UseTruncatedHMAC(WOLFSSL_CTX* ctx)
2789
{
2790
    if (ctx == NULL)
2791
        return BAD_FUNC_ARG;
2792
2793
    return TLSX_UseTruncatedHMAC(&ctx->extensions, ctx->heap);
2794
}
2795
2796
#endif /* NO_WOLFSSL_CLIENT */
2797
#endif /* HAVE_TRUNCATED_HMAC */
2798
2799
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST
2800
2801
int wolfSSL_UseOCSPStapling(WOLFSSL* ssl, byte status_type, byte options)
2802
{
2803
    WOLFSSL_ENTER("wolfSSL_UseOCSPStapling");
2804
2805
    if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
2806
        return BAD_FUNC_ARG;
2807
2808
    return TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
2809
                                          options, NULL, ssl->heap, ssl->devId);
2810
}
2811
2812
2813
int wolfSSL_CTX_UseOCSPStapling(WOLFSSL_CTX* ctx, byte status_type,
2814
                                                                   byte options)
2815
{
2816
    WOLFSSL_ENTER("wolfSSL_CTX_UseOCSPStapling");
2817
2818
    if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
2819
        return BAD_FUNC_ARG;
2820
2821
    return TLSX_UseCertificateStatusRequest(&ctx->extensions, status_type,
2822
                                          options, NULL, ctx->heap, ctx->devId);
2823
}
2824
2825
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
2826
2827
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
2828
2829
int wolfSSL_UseOCSPStaplingV2(WOLFSSL* ssl, byte status_type, byte options)
2830
{
2831
    if (ssl == NULL || ssl->options.side != WOLFSSL_CLIENT_END)
2832
        return BAD_FUNC_ARG;
2833
2834
    return TLSX_UseCertificateStatusRequestV2(&ssl->extensions, status_type,
2835
                                                options, ssl->heap, ssl->devId);
2836
}
2837
2838
2839
int wolfSSL_CTX_UseOCSPStaplingV2(WOLFSSL_CTX* ctx, byte status_type,
2840
                                                                   byte options)
2841
{
2842
    if (ctx == NULL || ctx->method->side != WOLFSSL_CLIENT_END)
2843
        return BAD_FUNC_ARG;
2844
2845
    return TLSX_UseCertificateStatusRequestV2(&ctx->extensions, status_type,
2846
                                                options, ctx->heap, ctx->devId);
2847
}
2848
2849
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
2850
2851
/* Elliptic Curves */
2852
#if defined(HAVE_SUPPORTED_CURVES)
2853
2854
static int isValidCurveGroup(word16 name)
2855
0
{
2856
0
    switch (name) {
2857
0
        case WOLFSSL_ECC_SECP160K1:
2858
0
        case WOLFSSL_ECC_SECP160R1:
2859
0
        case WOLFSSL_ECC_SECP160R2:
2860
0
        case WOLFSSL_ECC_SECP192K1:
2861
0
        case WOLFSSL_ECC_SECP192R1:
2862
0
        case WOLFSSL_ECC_SECP224K1:
2863
0
        case WOLFSSL_ECC_SECP224R1:
2864
0
        case WOLFSSL_ECC_SECP256K1:
2865
0
        case WOLFSSL_ECC_SECP256R1:
2866
0
        case WOLFSSL_ECC_SECP384R1:
2867
0
        case WOLFSSL_ECC_SECP521R1:
2868
0
        case WOLFSSL_ECC_BRAINPOOLP256R1:
2869
0
        case WOLFSSL_ECC_BRAINPOOLP384R1:
2870
0
        case WOLFSSL_ECC_BRAINPOOLP512R1:
2871
0
        case WOLFSSL_ECC_X25519:
2872
0
        case WOLFSSL_ECC_X448:
2873
2874
0
        case WOLFSSL_FFDHE_2048:
2875
0
        case WOLFSSL_FFDHE_3072:
2876
0
        case WOLFSSL_FFDHE_4096:
2877
0
        case WOLFSSL_FFDHE_6144:
2878
0
        case WOLFSSL_FFDHE_8192:
2879
2880
#ifdef HAVE_PQC
2881
        case WOLFSSL_KYBER_LEVEL1:
2882
        case WOLFSSL_KYBER_LEVEL3:
2883
        case WOLFSSL_KYBER_LEVEL5:
2884
    #ifdef HAVE_LIBOQS
2885
        case WOLFSSL_NTRU_HPS_LEVEL1:
2886
        case WOLFSSL_NTRU_HPS_LEVEL3:
2887
        case WOLFSSL_NTRU_HPS_LEVEL5:
2888
        case WOLFSSL_NTRU_HRSS_LEVEL3:
2889
        case WOLFSSL_SABER_LEVEL1:
2890
        case WOLFSSL_SABER_LEVEL3:
2891
        case WOLFSSL_SABER_LEVEL5:
2892
        case WOLFSSL_KYBER_90S_LEVEL1:
2893
        case WOLFSSL_KYBER_90S_LEVEL3:
2894
        case WOLFSSL_KYBER_90S_LEVEL5:
2895
        case WOLFSSL_P256_NTRU_HPS_LEVEL1:
2896
        case WOLFSSL_P384_NTRU_HPS_LEVEL3:
2897
        case WOLFSSL_P521_NTRU_HPS_LEVEL5:
2898
        case WOLFSSL_P384_NTRU_HRSS_LEVEL3:
2899
        case WOLFSSL_P256_SABER_LEVEL1:
2900
        case WOLFSSL_P384_SABER_LEVEL3:
2901
        case WOLFSSL_P521_SABER_LEVEL5:
2902
        case WOLFSSL_P256_KYBER_LEVEL1:
2903
        case WOLFSSL_P384_KYBER_LEVEL3:
2904
        case WOLFSSL_P521_KYBER_LEVEL5:
2905
        case WOLFSSL_P256_KYBER_90S_LEVEL1:
2906
        case WOLFSSL_P384_KYBER_90S_LEVEL3:
2907
        case WOLFSSL_P521_KYBER_90S_LEVEL5:
2908
    #endif
2909
#endif
2910
0
            return 1;
2911
2912
0
        default:
2913
0
            return 0;
2914
0
    }
2915
0
}
2916
2917
int wolfSSL_UseSupportedCurve(WOLFSSL* ssl, word16 name)
2918
0
{
2919
0
    if (ssl == NULL || !isValidCurveGroup(name))
2920
0
        return BAD_FUNC_ARG;
2921
2922
0
    ssl->options.userCurves = 1;
2923
#if defined(NO_TLS)
2924
    return WOLFSSL_FAILURE;
2925
#else
2926
0
    return TLSX_UseSupportedCurve(&ssl->extensions, name, ssl->heap);
2927
0
#endif /* NO_TLS */
2928
0
}
2929
2930
2931
int wolfSSL_CTX_UseSupportedCurve(WOLFSSL_CTX* ctx, word16 name)
2932
0
{
2933
0
    if (ctx == NULL || !isValidCurveGroup(name))
2934
0
        return BAD_FUNC_ARG;
2935
2936
0
    ctx->userCurves = 1;
2937
#if defined(NO_TLS)
2938
    return WOLFSSL_FAILURE;
2939
#else
2940
0
    return TLSX_UseSupportedCurve(&ctx->extensions, name, ctx->heap);
2941
0
#endif /* NO_TLS */
2942
0
}
2943
2944
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_TLS13)
2945
int  wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups,
2946
                                        int count)
2947
{
2948
    int i;
2949
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
2950
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
2951
    if (count == 0) {
2952
        WOLFSSL_MSG("Group count is zero");
2953
        return WOLFSSL_FAILURE;
2954
    }
2955
    for (i = 0; i < count; i++) {
2956
        if (isValidCurveGroup((word16)groups[i])) {
2957
            _groups[i] = groups[i];
2958
        }
2959
#ifdef HAVE_ECC
2960
        else {
2961
            /* groups may be populated with curve NIDs */
2962
            int oid = nid2oid(groups[i], oidCurveType);
2963
            int name = (int)GetCurveByOID(oid);
2964
            if (name == 0) {
2965
                WOLFSSL_MSG("Invalid group name");
2966
                return WOLFSSL_FAILURE;
2967
            }
2968
            _groups[i] = name;
2969
        }
2970
#else
2971
        else {
2972
            WOLFSSL_MSG("Invalid group name");
2973
            return WOLFSSL_FAILURE;
2974
        }
2975
#endif
2976
    }
2977
    return wolfSSL_CTX_set_groups(ctx, _groups, count) == WOLFSSL_SUCCESS ?
2978
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
2979
}
2980
2981
int  wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count)
2982
{
2983
    int i;
2984
    int _groups[WOLFSSL_MAX_GROUP_COUNT];
2985
    WOLFSSL_ENTER("wolfSSL_CTX_set1_groups");
2986
    if (count == 0) {
2987
        WOLFSSL_MSG("Group count is zero");
2988
        return WOLFSSL_FAILURE;
2989
    }
2990
    for (i = 0; i < count; i++) {
2991
        if (isValidCurveGroup((word16)groups[i])) {
2992
            _groups[i] = groups[i];
2993
        }
2994
#ifdef HAVE_ECC
2995
        else {
2996
            /* groups may be populated with curve NIDs */
2997
            int oid = nid2oid(groups[i], oidCurveType);
2998
            int name = (int)GetCurveByOID(oid);
2999
            if (name == 0) {
3000
                WOLFSSL_MSG("Invalid group name");
3001
                return WOLFSSL_FAILURE;
3002
            }
3003
            _groups[i] = name;
3004
        }
3005
#else
3006
        else {
3007
            WOLFSSL_MSG("Invalid group name");
3008
            return WOLFSSL_FAILURE;
3009
        }
3010
#endif
3011
    }
3012
    return wolfSSL_set_groups(ssl, _groups, count) == WOLFSSL_SUCCESS ?
3013
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3014
}
3015
#endif /* OPENSSL_EXTRA && WOLFSSL_TLS13 */
3016
#endif /* HAVE_SUPPORTED_CURVES */
3017
3018
/* Application-Layer Protocol Negotiation */
3019
#ifdef HAVE_ALPN
3020
3021
WOLFSSL_ABI
3022
int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list,
3023
                    word32 protocol_name_listSz, byte options)
3024
{
3025
    char    *list, *ptr, **token;
3026
    word16  len;
3027
    int     idx = 0;
3028
    int     ret = WOLFSSL_FAILURE;
3029
3030
    WOLFSSL_ENTER("wolfSSL_UseALPN");
3031
3032
    if (ssl == NULL || protocol_name_list == NULL)
3033
        return BAD_FUNC_ARG;
3034
3035
    if (protocol_name_listSz > (WOLFSSL_MAX_ALPN_NUMBER *
3036
                                WOLFSSL_MAX_ALPN_PROTO_NAME_LEN +
3037
                                WOLFSSL_MAX_ALPN_NUMBER)) {
3038
        WOLFSSL_MSG("Invalid arguments, protocol name list too long");
3039
        return BAD_FUNC_ARG;
3040
    }
3041
3042
    if (!(options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) &&
3043
        !(options & WOLFSSL_ALPN_FAILED_ON_MISMATCH)) {
3044
            WOLFSSL_MSG("Invalid arguments, options not supported");
3045
            return BAD_FUNC_ARG;
3046
        }
3047
3048
3049
    list = (char *)XMALLOC(protocol_name_listSz+1, ssl->heap,
3050
                           DYNAMIC_TYPE_ALPN);
3051
    if (list == NULL) {
3052
        WOLFSSL_MSG("Memory failure");
3053
        return MEMORY_ERROR;
3054
    }
3055
3056
    token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1), ssl->heap, DYNAMIC_TYPE_ALPN);
3057
    if (token == NULL) {
3058
        XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3059
        WOLFSSL_MSG("Memory failure");
3060
        return MEMORY_ERROR;
3061
    }
3062
    XMEMSET(token, 0, sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1));
3063
3064
    XSTRNCPY(list, protocol_name_list, protocol_name_listSz);
3065
    list[protocol_name_listSz] = '\0';
3066
3067
    /* read all protocol name from the list */
3068
    token[idx] = XSTRTOK(list, ",", &ptr);
3069
    while (idx < WOLFSSL_MAX_ALPN_NUMBER && token[idx] != NULL)
3070
        token[++idx] = XSTRTOK(NULL, ",", &ptr);
3071
3072
    /* add protocol name list in the TLS extension in reverse order */
3073
    while ((idx--) > 0) {
3074
        len = (word16)XSTRLEN(token[idx]);
3075
3076
        ret = TLSX_UseALPN(&ssl->extensions, token[idx], len, options,
3077
                                                                     ssl->heap);
3078
        if (ret != WOLFSSL_SUCCESS) {
3079
            WOLFSSL_MSG("TLSX_UseALPN failure");
3080
            break;
3081
        }
3082
    }
3083
3084
    XFREE(token, ssl->heap, DYNAMIC_TYPE_ALPN);
3085
    XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN);
3086
3087
    return ret;
3088
}
3089
3090
int wolfSSL_ALPN_GetProtocol(WOLFSSL* ssl, char **protocol_name, word16 *size)
3091
{
3092
    return TLSX_ALPN_GetRequest(ssl ? ssl->extensions : NULL,
3093
                               (void **)protocol_name, size);
3094
}
3095
3096
int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, word16 *listSz)
3097
{
3098
    if (list == NULL || listSz == NULL)
3099
        return BAD_FUNC_ARG;
3100
3101
    if (ssl->alpn_client_list == NULL)
3102
        return BUFFER_ERROR;
3103
3104
    *listSz = (word16)XSTRLEN(ssl->alpn_client_list);
3105
    if (*listSz == 0)
3106
        return BUFFER_ERROR;
3107
3108
    *list = (char *)XMALLOC((*listSz)+1, ssl->heap, DYNAMIC_TYPE_TLSX);
3109
    if (*list == NULL)
3110
        return MEMORY_ERROR;
3111
3112
    XSTRNCPY(*list, ssl->alpn_client_list, (*listSz)+1);
3113
    (*list)[*listSz] = 0;
3114
3115
    return WOLFSSL_SUCCESS;
3116
}
3117
3118
3119
/* used to free memory allocated by wolfSSL_ALPN_GetPeerProtocol */
3120
int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list)
3121
{
3122
    if (ssl == NULL) {
3123
        return BAD_FUNC_ARG;
3124
    }
3125
3126
    XFREE(*list, ssl->heap, DYNAMIC_TYPE_TLSX);
3127
    *list = NULL;
3128
3129
    return WOLFSSL_SUCCESS;
3130
}
3131
3132
#endif /* HAVE_ALPN */
3133
3134
/* Secure Renegotiation */
3135
#ifdef HAVE_SERVER_RENEGOTIATION_INFO
3136
3137
/* user is forcing ability to use secure renegotiation, we discourage it */
3138
int wolfSSL_UseSecureRenegotiation(WOLFSSL* ssl)
3139
0
{
3140
0
    int ret = BAD_FUNC_ARG;
3141
#if defined(NO_TLS)
3142
    (void)ssl;
3143
#else
3144
0
    if (ssl)
3145
0
        ret = TLSX_UseSecureRenegotiation(&ssl->extensions, ssl->heap);
3146
3147
0
    if (ret == WOLFSSL_SUCCESS) {
3148
0
        TLSX* extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
3149
3150
0
        if (extension)
3151
0
            ssl->secure_renegotiation = (SecureRenegotiation*)extension->data;
3152
0
    }
3153
0
#endif /* !NO_TLS */
3154
0
    return ret;
3155
0
}
3156
3157
int wolfSSL_CTX_UseSecureRenegotiation(WOLFSSL_CTX* ctx)
3158
0
{
3159
0
    if (ctx == NULL)
3160
0
        return BAD_FUNC_ARG;
3161
3162
0
    ctx->useSecureReneg = 1;
3163
0
    return WOLFSSL_SUCCESS;
3164
0
}
3165
3166
3167
/* do a secure renegotiation handshake, user forced, we discourage */
3168
static int _Rehandshake(WOLFSSL* ssl)
3169
0
{
3170
0
    int ret;
3171
3172
0
    if (ssl == NULL)
3173
0
        return BAD_FUNC_ARG;
3174
3175
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
3176
0
        WOLFSSL_MSG("Secure Renegotiation not supported in TLS 1.3");
3177
0
        return SECURE_RENEGOTIATION_E;
3178
0
    }
3179
3180
0
    if (ssl->secure_renegotiation == NULL) {
3181
0
        WOLFSSL_MSG("Secure Renegotiation not forced on by user");
3182
0
        return SECURE_RENEGOTIATION_E;
3183
0
    }
3184
3185
0
    if (ssl->secure_renegotiation->enabled == 0) {
3186
0
        WOLFSSL_MSG("Secure Renegotiation not enabled at extension level");
3187
0
        return SECURE_RENEGOTIATION_E;
3188
0
    }
3189
3190
#ifdef WOLFSSL_DTLS
3191
    if (ssl->options.dtls && ssl->keys.dtls_epoch == 0xFFFF) {
3192
        WOLFSSL_MSG("Secure Renegotiation not allowed. Epoch would wrap");
3193
        return SECURE_RENEGOTIATION_E;
3194
    }
3195
#endif
3196
3197
    /* If the client started the renegotiation, the server will already
3198
     * have processed the client's hello. */
3199
0
    if (ssl->options.side != WOLFSSL_SERVER_END ||
3200
0
        ssl->options.acceptState != ACCEPT_FIRST_REPLY_DONE) {
3201
3202
0
        if (ssl->options.handShakeState != HANDSHAKE_DONE) {
3203
0
            if (!ssl->options.handShakeDone) {
3204
0
                WOLFSSL_MSG("Can't renegotiate until initial "
3205
0
                            "handshake complete");
3206
0
                return SECURE_RENEGOTIATION_E;
3207
0
            }
3208
0
            else {
3209
0
                WOLFSSL_MSG("Renegotiation already started. "
3210
0
                            "Moving it forward.");
3211
0
                ret = wolfSSL_negotiate(ssl);
3212
0
                if (ret == WOLFSSL_SUCCESS)
3213
0
                    ssl->secure_rene_count++;
3214
0
                return ret;
3215
0
            }
3216
0
        }
3217
3218
0
#ifndef NO_FORCE_SCR_SAME_SUITE
3219
        /* force same suite */
3220
0
        if (ssl->suites) {
3221
0
            ssl->suites->suiteSz = SUITE_LEN;
3222
0
            ssl->suites->suites[0] = ssl->options.cipherSuite0;
3223
0
            ssl->suites->suites[1] = ssl->options.cipherSuite;
3224
0
        }
3225
0
#endif
3226
3227
        /* reset handshake states */
3228
0
        ssl->options.sendVerify = 0;
3229
0
        ssl->options.serverState = NULL_STATE;
3230
0
        ssl->options.clientState = NULL_STATE;
3231
0
        ssl->options.connectState  = CONNECT_BEGIN;
3232
0
        ssl->options.acceptState   = ACCEPT_BEGIN_RENEG;
3233
0
        ssl->options.handShakeState = NULL_STATE;
3234
0
        ssl->options.processReply  = 0;  /* TODO, move states in internal.h */
3235
3236
0
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
3237
3238
0
        ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
3239
3240
#if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SECURE_RENEGOTIATION)
3241
        if (ssl->options.side == WOLFSSL_SERVER_END) {
3242
            ret = SendHelloRequest(ssl);
3243
            if (ret != 0) {
3244
                ssl->error = ret;
3245
                return WOLFSSL_FATAL_ERROR;
3246
            }
3247
        }
3248
#endif /* !NO_WOLFSSL_SERVER && HAVE_SECURE_RENEGOTIATION */
3249
3250
0
        ret = InitHandshakeHashes(ssl);
3251
0
        if (ret != 0) {
3252
0
            ssl->error = ret;
3253
0
            return WOLFSSL_FATAL_ERROR;
3254
0
        }
3255
0
    }
3256
0
    ret = wolfSSL_negotiate(ssl);
3257
0
    if (ret == WOLFSSL_SUCCESS)
3258
0
        ssl->secure_rene_count++;
3259
0
    return ret;
3260
0
}
3261
3262
3263
/* do a secure renegotiation handshake, user forced, we discourage */
3264
int wolfSSL_Rehandshake(WOLFSSL* ssl)
3265
0
{
3266
0
    int ret;
3267
0
    WOLFSSL_ENTER("wolfSSL_Rehandshake");
3268
3269
0
    if (ssl == NULL)
3270
0
        return WOLFSSL_FAILURE;
3271
3272
#ifdef HAVE_SESSION_TICKET
3273
    ret = WOLFSSL_SUCCESS;
3274
#endif
3275
3276
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
3277
        /* Reset option to send certificate verify. */
3278
0
        ssl->options.sendVerify = 0;
3279
0
    }
3280
0
    else {
3281
        /* Reset resuming flag to do full secure handshake. */
3282
0
        ssl->options.resuming = 0;
3283
        #ifdef HAVE_SESSION_TICKET
3284
            /* Clearing the ticket. */
3285
            ret = wolfSSL_UseSessionTicket(ssl);
3286
        #endif
3287
0
    }
3288
    /* CLIENT/SERVER: Reset peer authentication for full secure handshake. */
3289
0
    ssl->options.peerAuthGood = 0;
3290
3291
#ifdef HAVE_SESSION_TICKET
3292
    if (ret == WOLFSSL_SUCCESS)
3293
#endif
3294
0
        ret = _Rehandshake(ssl);
3295
3296
0
    return ret;
3297
0
}
3298
3299
3300
#ifndef NO_WOLFSSL_CLIENT
3301
3302
/* do a secure resumption handshake, user forced, we discourage */
3303
int wolfSSL_SecureResume(WOLFSSL* ssl)
3304
0
{
3305
0
    WOLFSSL_ENTER("wolfSSL_SecureResume");
3306
3307
0
    if (ssl == NULL)
3308
0
        return BAD_FUNC_ARG;
3309
3310
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
3311
0
        ssl->error = SIDE_ERROR;
3312
0
        return WOLFSSL_FATAL_ERROR;
3313
0
    }
3314
3315
0
    return _Rehandshake(ssl);
3316
0
}
3317
3318
#endif /* NO_WOLFSSL_CLIENT */
3319
3320
long wolfSSL_SSL_get_secure_renegotiation_support(WOLFSSL* ssl)
3321
0
{
3322
0
    WOLFSSL_ENTER("wolfSSL_SSL_get_secure_renegotiation_support");
3323
3324
0
    if (!ssl || !ssl->secure_renegotiation)
3325
0
        return WOLFSSL_FAILURE;
3326
0
    return ssl->secure_renegotiation->enabled;
3327
0
}
3328
3329
#endif /* HAVE_SECURE_RENEGOTIATION_INFO */
3330
3331
#if defined(HAVE_SESSION_TICKET)
3332
/* Session Ticket */
3333
3334
#if !defined(NO_WOLFSSL_SERVER)
3335
int wolfSSL_CTX_NoTicketTLSv12(WOLFSSL_CTX* ctx)
3336
{
3337
    if (ctx == NULL)
3338
        return BAD_FUNC_ARG;
3339
3340
    ctx->noTicketTls12 = 1;
3341
3342
    return WOLFSSL_SUCCESS;
3343
}
3344
3345
int wolfSSL_NoTicketTLSv12(WOLFSSL* ssl)
3346
{
3347
    if (ssl == NULL)
3348
        return BAD_FUNC_ARG;
3349
3350
    ssl->options.noTicketTls12 = 1;
3351
3352
    return WOLFSSL_SUCCESS;
3353
}
3354
3355
/* WOLFSSL_SUCCESS on ok */
3356
int wolfSSL_CTX_set_TicketEncCb(WOLFSSL_CTX* ctx, SessionTicketEncCb cb)
3357
{
3358
    if (ctx == NULL)
3359
        return BAD_FUNC_ARG;
3360
3361
    ctx->ticketEncCb = cb;
3362
3363
    return WOLFSSL_SUCCESS;
3364
}
3365
3366
/* set hint interval, WOLFSSL_SUCCESS on ok */
3367
int wolfSSL_CTX_set_TicketHint(WOLFSSL_CTX* ctx, int hint)
3368
{
3369
    if (ctx == NULL)
3370
        return BAD_FUNC_ARG;
3371
3372
    ctx->ticketHint = hint;
3373
3374
    return WOLFSSL_SUCCESS;
3375
}
3376
3377
/* set user context, WOLFSSL_SUCCESS on ok */
3378
int wolfSSL_CTX_set_TicketEncCtx(WOLFSSL_CTX* ctx, void* userCtx)
3379
{
3380
    if (ctx == NULL)
3381
        return BAD_FUNC_ARG;
3382
3383
    ctx->ticketEncCtx = userCtx;
3384
3385
    return WOLFSSL_SUCCESS;
3386
}
3387
3388
/* get user context - returns userCtx on success, NULL on failure */
3389
void* wolfSSL_CTX_get_TicketEncCtx(WOLFSSL_CTX* ctx)
3390
{
3391
    if (ctx == NULL)
3392
        return NULL;
3393
3394
    return ctx->ticketEncCtx;
3395
}
3396
3397
#ifdef WOLFSSL_TLS13
3398
/* set the maximum number of tickets to send
3399
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on fail
3400
 */
3401
int wolfSSL_CTX_set_num_tickets(WOLFSSL_CTX* ctx, size_t mxTickets)
3402
{
3403
    if (ctx == NULL)
3404
        return WOLFSSL_FAILURE;
3405
3406
    ctx->maxTicketTls13 = (unsigned int)mxTickets;
3407
    return WOLFSSL_SUCCESS;
3408
}
3409
3410
/* get the maximum number of tickets to send
3411
 * return number of tickets set to be sent
3412
 */
3413
size_t wolfSSL_CTX_get_num_tickets(WOLFSSL_CTX* ctx)
3414
{
3415
    if (ctx == NULL)
3416
        return 0;
3417
3418
    return (size_t)ctx->maxTicketTls13;
3419
}
3420
#endif /* WOLFSSL_TLS13 */
3421
#endif /* !NO_WOLFSSL_SERVER */
3422
3423
#if !defined(NO_WOLFSSL_CLIENT)
3424
int wolfSSL_UseSessionTicket(WOLFSSL* ssl)
3425
{
3426
    if (ssl == NULL)
3427
        return BAD_FUNC_ARG;
3428
3429
    return TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
3430
}
3431
3432
int wolfSSL_CTX_UseSessionTicket(WOLFSSL_CTX* ctx)
3433
{
3434
    if (ctx == NULL)
3435
        return BAD_FUNC_ARG;
3436
3437
    return TLSX_UseSessionTicket(&ctx->extensions, NULL, ctx->heap);
3438
}
3439
3440
WOLFSSL_API int wolfSSL_get_SessionTicket(WOLFSSL* ssl,
3441
                                          byte* buf, word32* bufSz)
3442
{
3443
    if (ssl == NULL || buf == NULL || bufSz == NULL || *bufSz == 0)
3444
        return BAD_FUNC_ARG;
3445
3446
    if (ssl->session->ticketLen <= *bufSz) {
3447
        XMEMCPY(buf, ssl->session->ticket, ssl->session->ticketLen);
3448
        *bufSz = ssl->session->ticketLen;
3449
    }
3450
    else
3451
        *bufSz = 0;
3452
3453
    return WOLFSSL_SUCCESS;
3454
}
3455
3456
WOLFSSL_API int wolfSSL_set_SessionTicket(WOLFSSL* ssl, const byte* buf,
3457
                                          word32 bufSz)
3458
{
3459
    if (ssl == NULL || (buf == NULL && bufSz > 0))
3460
        return BAD_FUNC_ARG;
3461
3462
    if (bufSz > 0) {
3463
        /* Ticket will fit into static ticket */
3464
        if (bufSz <= SESSION_TICKET_LEN) {
3465
            if (ssl->session->ticketLenAlloc > 0) {
3466
                XFREE(ssl->session->ticket, ssl->session->heap,
3467
                      DYNAMIC_TYPE_SESSION_TICK);
3468
                ssl->session->ticketLenAlloc = 0;
3469
                ssl->session->ticket = ssl->session->staticTicket;
3470
            }
3471
        }
3472
        else { /* Ticket requires dynamic ticket storage */
3473
            if (ssl->session->ticketLen < bufSz) { /* is dyn buffer big enough */
3474
                if (ssl->session->ticketLenAlloc > 0) {
3475
                    XFREE(ssl->session->ticket, ssl->session->heap,
3476
                          DYNAMIC_TYPE_SESSION_TICK);
3477
                }
3478
                ssl->session->ticket = (byte*)XMALLOC(bufSz, ssl->session->heap,
3479
                        DYNAMIC_TYPE_SESSION_TICK);
3480
                if(ssl->session->ticket == NULL) {
3481
                    ssl->session->ticket = ssl->session->staticTicket;
3482
                    ssl->session->ticketLenAlloc = 0;
3483
                    return MEMORY_ERROR;
3484
                }
3485
                ssl->session->ticketLenAlloc = (word16)bufSz;
3486
            }
3487
        }
3488
        XMEMCPY(ssl->session->ticket, buf, bufSz);
3489
    }
3490
    ssl->session->ticketLen = (word16)bufSz;
3491
3492
    return WOLFSSL_SUCCESS;
3493
}
3494
3495
3496
WOLFSSL_API int wolfSSL_set_SessionTicket_cb(WOLFSSL* ssl,
3497
                                            CallbackSessionTicket cb, void* ctx)
3498
{
3499
    if (ssl == NULL)
3500
        return BAD_FUNC_ARG;
3501
3502
    ssl->session_ticket_cb = cb;
3503
    ssl->session_ticket_ctx = ctx;
3504
3505
    return WOLFSSL_SUCCESS;
3506
}
3507
#endif /* !NO_WOLFSSL_CLIENT */
3508
3509
#endif /* HAVE_SESSION_TICKET */
3510
3511
3512
#ifdef HAVE_EXTENDED_MASTER
3513
#ifndef NO_WOLFSSL_CLIENT
3514
3515
int wolfSSL_CTX_DisableExtendedMasterSecret(WOLFSSL_CTX* ctx)
3516
0
{
3517
0
    if (ctx == NULL)
3518
0
        return BAD_FUNC_ARG;
3519
3520
0
    ctx->haveEMS = 0;
3521
3522
0
    return WOLFSSL_SUCCESS;
3523
0
}
3524
3525
3526
int wolfSSL_DisableExtendedMasterSecret(WOLFSSL* ssl)
3527
0
{
3528
0
    if (ssl == NULL)
3529
0
        return BAD_FUNC_ARG;
3530
3531
0
    ssl->options.haveEMS = 0;
3532
3533
0
    return WOLFSSL_SUCCESS;
3534
0
}
3535
3536
#endif
3537
#endif
3538
3539
3540
#ifndef WOLFSSL_LEANPSK
3541
3542
int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags)
3543
0
{
3544
0
    int ret;
3545
0
    int oldFlags;
3546
3547
0
    WOLFSSL_ENTER("wolfSSL_send()");
3548
3549
0
    if (ssl == NULL || data == NULL || sz < 0)
3550
0
        return BAD_FUNC_ARG;
3551
3552
0
    oldFlags = ssl->wflags;
3553
3554
0
    ssl->wflags = flags;
3555
0
    ret = wolfSSL_write(ssl, data, sz);
3556
0
    ssl->wflags = oldFlags;
3557
3558
0
    WOLFSSL_LEAVE("wolfSSL_send()", ret);
3559
3560
0
    return ret;
3561
0
}
3562
3563
3564
int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags)
3565
0
{
3566
0
    int ret;
3567
0
    int oldFlags;
3568
3569
0
    WOLFSSL_ENTER("wolfSSL_recv()");
3570
3571
0
    if (ssl == NULL || data == NULL || sz < 0)
3572
0
        return BAD_FUNC_ARG;
3573
3574
0
    oldFlags = ssl->rflags;
3575
3576
0
    ssl->rflags = flags;
3577
0
    ret = wolfSSL_read(ssl, data, sz);
3578
0
    ssl->rflags = oldFlags;
3579
3580
0
    WOLFSSL_LEAVE("wolfSSL_recv()", ret);
3581
3582
0
    return ret;
3583
0
}
3584
#endif
3585
3586
3587
/* WOLFSSL_SUCCESS on ok */
3588
WOLFSSL_ABI
3589
int wolfSSL_shutdown(WOLFSSL* ssl)
3590
0
{
3591
0
    int  ret = WOLFSSL_FATAL_ERROR;
3592
0
    WOLFSSL_ENTER("SSL_shutdown()");
3593
3594
0
    if (ssl == NULL)
3595
0
        return WOLFSSL_FATAL_ERROR;
3596
3597
0
    if (ssl->options.quietShutdown) {
3598
0
        WOLFSSL_MSG("quiet shutdown, no close notify sent");
3599
0
        ret = WOLFSSL_SUCCESS;
3600
0
    }
3601
0
    else {
3602
        /* try to send close notify, not an error if can't */
3603
0
        if (!ssl->options.isClosed && !ssl->options.connReset &&
3604
0
                                      !ssl->options.sentNotify) {
3605
0
            ssl->error = SendAlert(ssl, alert_warning, close_notify);
3606
0
            if (ssl->error < 0) {
3607
0
                WOLFSSL_ERROR(ssl->error);
3608
0
                return WOLFSSL_FATAL_ERROR;
3609
0
            }
3610
0
            ssl->options.sentNotify = 1;  /* don't send close_notify twice */
3611
0
            if (ssl->options.closeNotify)
3612
0
                ret = WOLFSSL_SUCCESS;
3613
0
            else {
3614
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
3615
0
                WOLFSSL_LEAVE("SSL_shutdown()", ret);
3616
0
                return ret;
3617
0
            }
3618
0
        }
3619
3620
#ifdef WOLFSSL_SHUTDOWNONCE
3621
        if (ssl->options.isClosed || ssl->options.connReset) {
3622
            /* Shutdown has already occurred.
3623
             * Caller is free to ignore this error. */
3624
            return SSL_SHUTDOWN_ALREADY_DONE_E;
3625
        }
3626
#endif
3627
3628
        /* call wolfSSL_shutdown again for bidirectional shutdown */
3629
0
        if (ssl->options.sentNotify && !ssl->options.closeNotify) {
3630
0
            ret = ProcessReply(ssl);
3631
0
            if (ret == ZERO_RETURN) {
3632
                /* simulate OpenSSL behavior */
3633
0
                ssl->error = WOLFSSL_ERROR_SYSCALL;
3634
0
                ret = WOLFSSL_SUCCESS;
3635
0
            } else if (ssl->error == WOLFSSL_ERROR_NONE) {
3636
0
                ret = WOLFSSL_SHUTDOWN_NOT_DONE;
3637
0
            } else {
3638
0
                WOLFSSL_ERROR(ssl->error);
3639
0
                ret = WOLFSSL_FATAL_ERROR;
3640
0
            }
3641
0
        }
3642
0
    }
3643
3644
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
3645
    /* reset WOLFSSL structure state for possible re-use */
3646
    if (ret == WOLFSSL_SUCCESS) {
3647
        if (wolfSSL_clear(ssl) != WOLFSSL_SUCCESS) {
3648
            WOLFSSL_MSG("could not clear WOLFSSL");
3649
            ret = WOLFSSL_FATAL_ERROR;
3650
        }
3651
    }
3652
#endif
3653
3654
0
    WOLFSSL_LEAVE("SSL_shutdown()", ret);
3655
3656
0
    return ret;
3657
0
}
3658
3659
3660
/* get current error state value */
3661
int wolfSSL_state(WOLFSSL* ssl)
3662
0
{
3663
0
    if (ssl == NULL) {
3664
0
        return BAD_FUNC_ARG;
3665
0
    }
3666
3667
0
    return ssl->error;
3668
0
}
3669
3670
3671
WOLFSSL_ABI
3672
int wolfSSL_get_error(WOLFSSL* ssl, int ret)
3673
0
{
3674
0
    WOLFSSL_ENTER("SSL_get_error");
3675
3676
0
    if (ret > 0)
3677
0
        return WOLFSSL_ERROR_NONE;
3678
0
    if (ssl == NULL)
3679
0
        return BAD_FUNC_ARG;
3680
3681
0
    WOLFSSL_LEAVE("SSL_get_error", ssl->error);
3682
3683
    /* make sure converted types are handled in SetErrorString() too */
3684
0
    if (ssl->error == WANT_READ)
3685
0
        return WOLFSSL_ERROR_WANT_READ;         /* convert to OpenSSL type */
3686
0
    else if (ssl->error == WANT_WRITE)
3687
0
        return WOLFSSL_ERROR_WANT_WRITE;        /* convert to OpenSSL type */
3688
0
    else if (ssl->error == ZERO_RETURN)
3689
0
        return WOLFSSL_ERROR_ZERO_RETURN;       /* convert to OpenSSL type */
3690
0
    return ssl->error;
3691
0
}
3692
3693
3694
/* retrieve alert history, WOLFSSL_SUCCESS on ok */
3695
int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
3696
0
{
3697
0
    if (ssl && h) {
3698
0
        *h = ssl->alert_history;
3699
0
    }
3700
0
    return WOLFSSL_SUCCESS;
3701
0
}
3702
3703
#ifdef OPENSSL_EXTRA
3704
/* returns SSL_WRITING, SSL_READING or SSL_NOTHING */
3705
int wolfSSL_want(WOLFSSL* ssl)
3706
{
3707
    int rw_state = SSL_NOTHING;
3708
    if (ssl) {
3709
        if (ssl->error == WANT_READ)
3710
            rw_state = SSL_READING;
3711
        else if (ssl->error == WANT_WRITE)
3712
            rw_state = SSL_WRITING;
3713
    }
3714
    return rw_state;
3715
}
3716
#endif
3717
3718
/* return TRUE if current error is want read */
3719
int wolfSSL_want_read(WOLFSSL* ssl)
3720
0
{
3721
0
    WOLFSSL_ENTER("SSL_want_read");
3722
0
    if (ssl->error == WANT_READ)
3723
0
        return 1;
3724
3725
0
    return 0;
3726
0
}
3727
3728
3729
/* return TRUE if current error is want write */
3730
int wolfSSL_want_write(WOLFSSL* ssl)
3731
0
{
3732
0
    WOLFSSL_ENTER("SSL_want_write");
3733
0
    if (ssl->error == WANT_WRITE)
3734
0
        return 1;
3735
3736
0
    return 0;
3737
0
}
3738
3739
3740
char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data)
3741
0
{
3742
0
    static char tmp[WOLFSSL_MAX_ERROR_SZ] = {0};
3743
3744
0
    WOLFSSL_ENTER("ERR_error_string");
3745
0
    if (data) {
3746
0
        SetErrorString((int)errNumber, data);
3747
0
        return data;
3748
0
    }
3749
0
    else {
3750
0
        SetErrorString((int)errNumber, tmp);
3751
0
        return tmp;
3752
0
    }
3753
0
}
3754
3755
3756
void wolfSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
3757
0
{
3758
0
    WOLFSSL_ENTER("wolfSSL_ERR_error_string_n");
3759
0
    if (len >= WOLFSSL_MAX_ERROR_SZ)
3760
0
        wolfSSL_ERR_error_string(e, buf);
3761
0
    else {
3762
0
        char tmp[WOLFSSL_MAX_ERROR_SZ];
3763
3764
0
        WOLFSSL_MSG("Error buffer too short, truncating");
3765
0
        if (len) {
3766
0
            wolfSSL_ERR_error_string(e, tmp);
3767
0
            XMEMCPY(buf, tmp, len-1);
3768
0
            buf[len-1] = '\0';
3769
0
        }
3770
0
    }
3771
0
}
3772
3773
3774
/* don't free temporary arrays at end of handshake */
3775
void wolfSSL_KeepArrays(WOLFSSL* ssl)
3776
0
{
3777
0
    if (ssl)
3778
0
        ssl->options.saveArrays = 1;
3779
0
}
3780
3781
3782
/* user doesn't need temporary arrays anymore, Free */
3783
void wolfSSL_FreeArrays(WOLFSSL* ssl)
3784
0
{
3785
0
    if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
3786
0
        ssl->options.saveArrays = 0;
3787
0
        FreeArrays(ssl, 1);
3788
0
    }
3789
0
}
3790
3791
/* Set option to indicate that the resources are not to be freed after
3792
 * handshake.
3793
 *
3794
 * ssl  The SSL/TLS object.
3795
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
3796
 */
3797
int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
3798
0
{
3799
0
    if (ssl == NULL)
3800
0
        return BAD_FUNC_ARG;
3801
3802
0
    ssl->options.keepResources = 1;
3803
3804
0
    return 0;
3805
0
}
3806
3807
/* Free the handshake resources after handshake.
3808
 *
3809
 * ssl  The SSL/TLS object.
3810
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
3811
 */
3812
int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
3813
0
{
3814
0
    if (ssl == NULL)
3815
0
        return BAD_FUNC_ARG;
3816
3817
0
    FreeHandshakeResources(ssl);
3818
3819
0
    return 0;
3820
0
}
3821
3822
/* Use the client's order of preference when matching cipher suites.
3823
 *
3824
 * ssl  The SSL/TLS context object.
3825
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
3826
 */
3827
int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
3828
0
{
3829
0
    if (ctx == NULL)
3830
0
        return BAD_FUNC_ARG;
3831
3832
0
    ctx->useClientOrder = 1;
3833
3834
0
    return 0;
3835
0
}
3836
3837
/* Use the client's order of preference when matching cipher suites.
3838
 *
3839
 * ssl  The SSL/TLS object.
3840
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
3841
 */
3842
int wolfSSL_UseClientSuites(WOLFSSL* ssl)
3843
0
{
3844
0
    if (ssl == NULL)
3845
0
        return BAD_FUNC_ARG;
3846
3847
0
    ssl->options.useClientOrder = 1;
3848
3849
0
    return 0;
3850
0
}
3851
3852
#ifdef WOLFSSL_DTLS
3853
const byte* wolfSSL_GetDtlsMacSecret(WOLFSSL* ssl, int verify, int epochOrder)
3854
{
3855
#ifndef WOLFSSL_AEAD_ONLY
3856
    Keys* keys = NULL;
3857
3858
    (void)epochOrder;
3859
3860
    if (ssl == NULL)
3861
        return NULL;
3862
3863
#ifdef HAVE_SECURE_RENEGOTIATION
3864
    switch (epochOrder) {
3865
    case PEER_ORDER:
3866
        if (IsDtlsMsgSCRKeys(ssl))
3867
            keys = &ssl->secure_renegotiation->tmp_keys;
3868
        else
3869
            keys = &ssl->keys;
3870
        break;
3871
    case PREV_ORDER:
3872
        keys = &ssl->keys;
3873
        break;
3874
    case CUR_ORDER:
3875
        if (DtlsUseSCRKeys(ssl))
3876
            keys = &ssl->secure_renegotiation->tmp_keys;
3877
        else
3878
            keys = &ssl->keys;
3879
        break;
3880
    default:
3881
        WOLFSSL_MSG("Unknown epoch order");
3882
        return NULL;
3883
    }
3884
#else
3885
    keys = &ssl->keys;
3886
#endif
3887
3888
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
3889
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
3890
        return keys->client_write_MAC_secret;
3891
    else
3892
        return keys->server_write_MAC_secret;
3893
#else
3894
    (void)ssl;
3895
    (void)verify;
3896
    (void)epochOrder;
3897
3898
    return NULL;
3899
#endif
3900
}
3901
#endif /* WOLFSSL_DTLS */
3902
3903
const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
3904
0
{
3905
0
#ifndef WOLFSSL_AEAD_ONLY
3906
0
    if (ssl == NULL)
3907
0
        return NULL;
3908
3909
0
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
3910
0
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
3911
0
        return ssl->keys.client_write_MAC_secret;
3912
0
    else
3913
0
        return ssl->keys.server_write_MAC_secret;
3914
#else
3915
    (void)ssl;
3916
    (void)verify;
3917
3918
    return NULL;
3919
#endif
3920
0
}
3921
3922
int wolfSSL_GetSide(WOLFSSL* ssl)
3923
0
{
3924
0
    if (ssl)
3925
0
        return ssl->options.side;
3926
3927
0
    return BAD_FUNC_ARG;
3928
0
}
3929
3930
#ifdef ATOMIC_USER
3931
3932
void  wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
3933
{
3934
    if (ctx)
3935
        ctx->MacEncryptCb = cb;
3936
}
3937
3938
3939
void  wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
3940
{
3941
    if (ssl)
3942
        ssl->MacEncryptCtx = ctx;
3943
}
3944
3945
3946
void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
3947
{
3948
    if (ssl)
3949
        return ssl->MacEncryptCtx;
3950
3951
    return NULL;
3952
}
3953
3954
3955
void  wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
3956
{
3957
    if (ctx)
3958
        ctx->DecryptVerifyCb = cb;
3959
}
3960
3961
3962
void  wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
3963
{
3964
    if (ssl)
3965
        ssl->DecryptVerifyCtx = ctx;
3966
}
3967
3968
3969
void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
3970
{
3971
    if (ssl)
3972
        return ssl->DecryptVerifyCtx;
3973
3974
    return NULL;
3975
}
3976
3977
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
3978
/**
3979
 * Set the callback, against the context, that encrypts then MACs.
3980
 *
3981
 * ctx  SSL/TLS context.
3982
 * cb   Callback function to use with Encrypt-Then-MAC.
3983
 */
3984
void  wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
3985
{
3986
    if (ctx)
3987
        ctx->EncryptMacCb = cb;
3988
}
3989
3990
/**
3991
 * Set the context to use with callback that encrypts then MACs.
3992
 *
3993
 * ssl  SSL/TLS object.
3994
 * ctx  Callback function's context.
3995
 */
3996
void  wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
3997
{
3998
    if (ssl)
3999
        ssl->EncryptMacCtx = ctx;
4000
}
4001
4002
/**
4003
 * Get the context being used with callback that encrypts then MACs.
4004
 *
4005
 * ssl  SSL/TLS object.
4006
 * returns callback function's context or NULL if SSL/TLS object is NULL.
4007
 */
4008
void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
4009
{
4010
    if (ssl)
4011
        return ssl->EncryptMacCtx;
4012
4013
    return NULL;
4014
}
4015
4016
4017
/**
4018
 * Set the callback, against the context, that MAC verifies then decrypts.
4019
 *
4020
 * ctx  SSL/TLS context.
4021
 * cb   Callback function to use with Encrypt-Then-MAC.
4022
 */
4023
void  wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
4024
{
4025
    if (ctx)
4026
        ctx->VerifyDecryptCb = cb;
4027
}
4028
4029
/**
4030
 * Set the context to use with callback that MAC verifies then decrypts.
4031
 *
4032
 * ssl  SSL/TLS object.
4033
 * ctx  Callback function's context.
4034
 */
4035
void  wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
4036
{
4037
    if (ssl)
4038
        ssl->VerifyDecryptCtx = ctx;
4039
}
4040
4041
/**
4042
 * Get the context being used with callback that MAC verifies then decrypts.
4043
 *
4044
 * ssl  SSL/TLS object.
4045
 * returns callback function's context or NULL if SSL/TLS object is NULL.
4046
 */
4047
void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
4048
{
4049
    if (ssl)
4050
        return ssl->VerifyDecryptCtx;
4051
4052
    return NULL;
4053
}
4054
#endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
4055
4056
4057
4058
const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
4059
{
4060
    if (ssl)
4061
        return ssl->keys.client_write_key;
4062
4063
    return NULL;
4064
}
4065
4066
4067
const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
4068
{
4069
    if (ssl)
4070
        return ssl->keys.client_write_IV;
4071
4072
    return NULL;
4073
}
4074
4075
4076
const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
4077
{
4078
    if (ssl)
4079
        return ssl->keys.server_write_key;
4080
4081
    return NULL;
4082
}
4083
4084
4085
const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
4086
{
4087
    if (ssl)
4088
        return ssl->keys.server_write_IV;
4089
4090
    return NULL;
4091
}
4092
4093
int wolfSSL_GetKeySize(WOLFSSL* ssl)
4094
{
4095
    if (ssl)
4096
        return ssl->specs.key_size;
4097
4098
    return BAD_FUNC_ARG;
4099
}
4100
4101
4102
int wolfSSL_GetIVSize(WOLFSSL* ssl)
4103
{
4104
    if (ssl)
4105
        return ssl->specs.iv_size;
4106
4107
    return BAD_FUNC_ARG;
4108
}
4109
4110
4111
int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
4112
{
4113
    if (ssl)
4114
        return ssl->specs.bulk_cipher_algorithm;
4115
4116
    return BAD_FUNC_ARG;
4117
}
4118
4119
4120
int wolfSSL_GetCipherType(WOLFSSL* ssl)
4121
{
4122
    if (ssl == NULL)
4123
        return BAD_FUNC_ARG;
4124
4125
#ifndef WOLFSSL_AEAD_ONLY
4126
    if (ssl->specs.cipher_type == block)
4127
        return WOLFSSL_BLOCK_TYPE;
4128
    if (ssl->specs.cipher_type == stream)
4129
        return WOLFSSL_STREAM_TYPE;
4130
#endif
4131
    if (ssl->specs.cipher_type == aead)
4132
        return WOLFSSL_AEAD_TYPE;
4133
4134
    return -1;
4135
}
4136
4137
4138
int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
4139
{
4140
    if (ssl == NULL)
4141
        return BAD_FUNC_ARG;
4142
4143
    return ssl->specs.block_size;
4144
}
4145
4146
4147
int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
4148
{
4149
    if (ssl == NULL)
4150
        return BAD_FUNC_ARG;
4151
4152
    return ssl->specs.aead_mac_size;
4153
}
4154
4155
4156
int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
4157
{
4158
    if (ssl == NULL)
4159
        return BAD_FUNC_ARG;
4160
4161
    if (ssl->options.tls1_1)
4162
        return 1;
4163
4164
    return 0;
4165
}
4166
4167
4168
4169
int wolfSSL_GetHmacSize(WOLFSSL* ssl)
4170
{
4171
    /* AEAD ciphers don't have HMAC keys */
4172
    if (ssl)
4173
        return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
4174
4175
    return BAD_FUNC_ARG;
4176
}
4177
4178
#ifdef WORD64_AVAILABLE
4179
int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
4180
{
4181
    if ((ssl == NULL) || (seq == NULL))
4182
        return BAD_FUNC_ARG;
4183
4184
    *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
4185
                    ssl->keys.peer_sequence_number_lo;
4186
    return !(*seq);
4187
}
4188
4189
int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
4190
{
4191
    if ((ssl == NULL) || (seq == NULL))
4192
        return BAD_FUNC_ARG;
4193
4194
    *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
4195
                    ssl->keys.sequence_number_lo;
4196
    return !(*seq);
4197
}
4198
#endif
4199
4200
#endif /* ATOMIC_USER */
4201
4202
#ifndef NO_CERTS
4203
4204
WOLFSSL_CERT_MANAGER* wolfSSL_CTX_GetCertManager(WOLFSSL_CTX* ctx)
4205
0
{
4206
0
    WOLFSSL_CERT_MANAGER* cm = NULL;
4207
0
    if (ctx)
4208
0
        cm = ctx->cm;
4209
0
    return cm;
4210
0
}
4211
4212
WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew_ex(void* heap)
4213
0
{
4214
0
    WOLFSSL_CERT_MANAGER* cm;
4215
4216
0
    WOLFSSL_ENTER("wolfSSL_CertManagerNew");
4217
4218
0
    cm = (WOLFSSL_CERT_MANAGER*) XMALLOC(sizeof(WOLFSSL_CERT_MANAGER), heap,
4219
0
                                         DYNAMIC_TYPE_CERT_MANAGER);
4220
0
    if (cm) {
4221
0
        XMEMSET(cm, 0, sizeof(WOLFSSL_CERT_MANAGER));
4222
0
        cm->refCount = 1;
4223
4224
0
        if (wc_InitMutex(&cm->caLock) != 0) {
4225
0
            WOLFSSL_MSG("Bad mutex init");
4226
0
            wolfSSL_CertManagerFree(cm);
4227
0
            return NULL;
4228
0
        }
4229
0
        #ifndef SINGLE_THREADED
4230
0
        if (wc_InitMutex(&cm->refMutex) != 0) {
4231
0
            WOLFSSL_MSG("Bad mutex init");
4232
0
            wolfSSL_CertManagerFree(cm);
4233
0
            return NULL;
4234
0
        }
4235
0
        #endif
4236
4237
        #ifdef WOLFSSL_TRUST_PEER_CERT
4238
        if (wc_InitMutex(&cm->tpLock) != 0) {
4239
            WOLFSSL_MSG("Bad mutex init");
4240
            wolfSSL_CertManagerFree(cm);
4241
            return NULL;
4242
        }
4243
        #endif
4244
4245
        /* set default minimum key size allowed */
4246
0
        #ifndef NO_RSA
4247
0
            cm->minRsaKeySz = MIN_RSAKEY_SZ;
4248
0
        #endif
4249
0
        #ifdef HAVE_ECC
4250
0
            cm->minEccKeySz = MIN_ECCKEY_SZ;
4251
0
        #endif
4252
        #ifdef HAVE_PQC
4253
        #ifdef HAVE_FALCON
4254
            cm->minFalconKeySz = MIN_FALCONKEY_SZ;
4255
        #endif /* HAVE_FALCON */
4256
        #ifdef HAVE_DILITHIUM
4257
            cm->minDilithiumKeySz = MIN_DILITHIUMKEY_SZ;
4258
        #endif /* HAVE_DILITHIUM */
4259
        #endif /* HAVE_PQC */
4260
4261
0
            cm->heap = heap;
4262
0
    }
4263
4264
0
    return cm;
4265
0
}
4266
4267
4268
WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew(void)
4269
0
{
4270
0
    return wolfSSL_CertManagerNew_ex(NULL);
4271
0
}
4272
4273
4274
void wolfSSL_CertManagerFree(WOLFSSL_CERT_MANAGER* cm)
4275
0
{
4276
0
    int doFree = 0;
4277
0
    WOLFSSL_ENTER("wolfSSL_CertManagerFree");
4278
4279
0
    if (cm) {
4280
0
        #ifndef SINGLE_THREADED
4281
0
        if (wc_LockMutex(&cm->refMutex) != 0) {
4282
0
            WOLFSSL_MSG("Couldn't lock cm mutex");
4283
0
        }
4284
0
        #endif
4285
0
        cm->refCount--;
4286
0
        if (cm->refCount == 0)
4287
0
            doFree = 1;
4288
0
        #ifndef SINGLE_THREADED
4289
0
        wc_UnLockMutex(&cm->refMutex);
4290
0
        #endif
4291
0
        if (doFree) {
4292
            #ifdef HAVE_CRL
4293
                if (cm->crl)
4294
                    FreeCRL(cm->crl, 1);
4295
            #endif
4296
            #ifdef HAVE_OCSP
4297
                if (cm->ocsp)
4298
                    FreeOCSP(cm->ocsp, 1);
4299
                XFREE(cm->ocspOverrideURL, cm->heap, DYNAMIC_TYPE_URL);
4300
            #if !defined(NO_WOLFSSL_SERVER) && \
4301
                (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
4302
                 defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
4303
                if (cm->ocsp_stapling)
4304
                    FreeOCSP(cm->ocsp_stapling, 1);
4305
            #endif
4306
            #endif
4307
0
            FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap);
4308
0
            wc_FreeMutex(&cm->caLock);
4309
4310
            #ifdef WOLFSSL_TRUST_PEER_CERT
4311
            FreeTrustedPeerTable(cm->tpTable, TP_TABLE_SIZE, cm->heap);
4312
            wc_FreeMutex(&cm->tpLock);
4313
            #endif
4314
0
            #ifndef SINGLE_THREADED
4315
0
            if (wc_FreeMutex(&cm->refMutex) != 0) {
4316
0
                WOLFSSL_MSG("Couldn't free refMutex mutex");
4317
0
            }
4318
0
            #endif
4319
0
            XFREE(cm, cm->heap, DYNAMIC_TYPE_CERT_MANAGER);
4320
0
        }
4321
0
    }
4322
4323
0
}
4324
4325
int wolfSSL_CertManager_up_ref(WOLFSSL_CERT_MANAGER* cm)
4326
0
{
4327
0
    if (cm) {
4328
0
#ifndef SINGLE_THREADED
4329
0
        if (wc_LockMutex(&cm->refMutex) != 0) {
4330
0
            WOLFSSL_MSG("Failed to lock cm mutex");
4331
0
            return WOLFSSL_FAILURE;
4332
0
        }
4333
0
#endif
4334
0
        cm->refCount++;
4335
0
#ifndef SINGLE_THREADED
4336
0
        wc_UnLockMutex(&cm->refMutex);
4337
0
#endif
4338
4339
0
        return WOLFSSL_SUCCESS;
4340
0
    }
4341
4342
0
    return WOLFSSL_FAILURE;
4343
0
}
4344
4345
#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM)
4346
#if defined(WOLFSSL_SIGNER_DER_CERT)
4347
/******************************************************************************
4348
* wolfSSL_CertManagerGetCerts - retrieve stack of X509 certificates in a
4349
* certificate manager (CM).
4350
*
4351
* RETURNS:
4352
* returns stack of X509 certs on success, otherwise returns a NULL.
4353
*/
4354
WOLFSSL_STACK* wolfSSL_CertManagerGetCerts(WOLFSSL_CERT_MANAGER* cm)
4355
{
4356
    WOLFSSL_STACK* sk = NULL;
4357
    int numCerts = 0;
4358
    DerBuffer** certBuffers = NULL;
4359
    const byte* derBuffer = NULL;
4360
    Signer* signers = NULL;
4361
    word32  row = 0;
4362
    WOLFSSL_X509* x509 = NULL;
4363
    int i = 0;
4364
    int ret = 0;
4365
4366
    if (cm == NULL)
4367
        return NULL;
4368
4369
    sk = wolfSSL_sk_X509_new_null();
4370
    if (sk == NULL)
4371
        goto error;
4372
4373
    if (wc_LockMutex(&cm->caLock) != 0)
4374
        goto error;
4375
4376
    /* Iterate once to get the number of certs, for memory allocation
4377
       purposes. */
4378
    for (row = 0; row < CA_TABLE_SIZE; row++) {
4379
        signers = cm->caTable[row];
4380
        while (signers && signers->derCert && signers->derCert->buffer) {
4381
            ++numCerts;
4382
            signers = signers->next;
4383
        }
4384
    }
4385
4386
    if (numCerts == 0) {
4387
        wc_UnLockMutex(&cm->caLock);
4388
        goto error;
4389
    }
4390
4391
    certBuffers = (DerBuffer**)XMALLOC(sizeof(DerBuffer*) * numCerts, cm->heap,
4392
                                       DYNAMIC_TYPE_TMP_BUFFER);
4393
    if (certBuffers == NULL) {
4394
        wc_UnLockMutex(&cm->caLock);
4395
        goto error;
4396
    }
4397
    XMEMSET(certBuffers, 0, sizeof(DerBuffer*) * numCerts);
4398
4399
    /* Copy the certs locally so that we can release the caLock. If the lock is
4400
       held when wolfSSL_d2i_X509 is called, GetCA will also try to get the
4401
       lock, leading to deadlock. */
4402
    for (row = 0; row < CA_TABLE_SIZE; row++) {
4403
        signers = cm->caTable[row];
4404
        while (signers && signers->derCert && signers->derCert->buffer) {
4405
            ret = AllocDer(&certBuffers[i], signers->derCert->length, CA_TYPE,
4406
                           cm->heap);
4407
            if (ret < 0) {
4408
                wc_UnLockMutex(&cm->caLock);
4409
                goto error;
4410
            }
4411
4412
            XMEMCPY(certBuffers[i]->buffer, signers->derCert->buffer,
4413
                    signers->derCert->length);
4414
            certBuffers[i]->length = signers->derCert->length;
4415
4416
            ++i;
4417
            signers = signers->next;
4418
        }
4419
    }
4420
4421
    wc_UnLockMutex(&cm->caLock);
4422
4423
    for (i = 0; i < numCerts; ++i) {
4424
        derBuffer = certBuffers[i]->buffer;
4425
        wolfSSL_d2i_X509(&x509, &derBuffer, certBuffers[i]->length);
4426
        if (x509 == NULL)
4427
            goto error;
4428
4429
        if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS)
4430
            goto error;
4431
    }
4432
4433
    for (i = 0; i < numCerts && certBuffers[i] != NULL; ++i) {
4434
        FreeDer(&certBuffers[i]);
4435
    }
4436
4437
    XFREE(certBuffers, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
4438
4439
    return sk;
4440
4441
error:
4442
    if (sk)
4443
        wolfSSL_sk_X509_pop_free(sk, NULL);
4444
4445
    if (certBuffers != NULL) {
4446
        for (i = 0; i < numCerts && certBuffers[i] != NULL; ++i) {
4447
            FreeDer(&certBuffers[i]);
4448
        }
4449
    }
4450
4451
    if (certBuffers)
4452
        XFREE(certBuffers, cm->heap, DYNAMIC_TYPE_TMP_BUFFER);
4453
4454
    return NULL;
4455
}
4456
4457
#endif /* WOLFSSL_SIGNER_DER_CERT */
4458
#endif /* OPENSSL_EXTRA && !NO_FILESYSTEM */
4459
4460
/* Unload the CA signer list */
4461
int wolfSSL_CertManagerUnloadCAs(WOLFSSL_CERT_MANAGER* cm)
4462
0
{
4463
0
    WOLFSSL_ENTER("wolfSSL_CertManagerUnloadCAs");
4464
4465
0
    if (cm == NULL)
4466
0
        return BAD_FUNC_ARG;
4467
4468
0
    if (wc_LockMutex(&cm->caLock) != 0)
4469
0
        return BAD_MUTEX_E;
4470
4471
0
    FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap);
4472
4473
0
    wc_UnLockMutex(&cm->caLock);
4474
4475
4476
0
    return WOLFSSL_SUCCESS;
4477
0
}
4478
4479
4480
#ifdef WOLFSSL_TRUST_PEER_CERT
4481
int wolfSSL_CertManagerUnload_trust_peers(WOLFSSL_CERT_MANAGER* cm)
4482
{
4483
    WOLFSSL_ENTER("wolfSSL_CertManagerUnload_trust_peers");
4484
4485
    if (cm == NULL)
4486
        return BAD_FUNC_ARG;
4487
4488
    if (wc_LockMutex(&cm->tpLock) != 0)
4489
        return BAD_MUTEX_E;
4490
4491
    FreeTrustedPeerTable(cm->tpTable, TP_TABLE_SIZE, cm->heap);
4492
4493
    wc_UnLockMutex(&cm->tpLock);
4494
4495
4496
    return WOLFSSL_SUCCESS;
4497
}
4498
#endif /* WOLFSSL_TRUST_PEER_CERT */
4499
4500
#endif /* NO_CERTS */
4501
4502
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
4503
4504
void wolfSSL_ERR_print_errors_fp(XFILE fp, int err)
4505
0
{
4506
0
    char data[WOLFSSL_MAX_ERROR_SZ + 1];
4507
4508
0
    WOLFSSL_ENTER("wolfSSL_ERR_print_errors_fp");
4509
0
    SetErrorString(err, data);
4510
0
    if (XFPRINTF(fp, "%s", data) < 0)
4511
0
        WOLFSSL_MSG("fprintf failed in wolfSSL_ERR_print_errors_fp");
4512
0
}
4513
4514
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
4515
void wolfSSL_ERR_dump_errors_fp(XFILE fp)
4516
{
4517
    wc_ERR_print_errors_fp(fp);
4518
}
4519
4520
void wolfSSL_ERR_print_errors_cb (int (*cb)(const char *str, size_t len,
4521
                                            void *u), void *u)
4522
{
4523
    wc_ERR_print_errors_cb(cb, u);
4524
}
4525
#endif
4526
#endif
4527
4528
/*
4529
 * TODO This ssl parameter needs to be changed to const once our ABI checker
4530
 *      stops flagging qualifier additions as ABI breaking.
4531
 */
4532
WOLFSSL_ABI
4533
int wolfSSL_pending(WOLFSSL* ssl)
4534
0
{
4535
0
    WOLFSSL_ENTER("SSL_pending");
4536
0
    if (ssl == NULL)
4537
0
        return WOLFSSL_FAILURE;
4538
4539
0
    return ssl->buffers.clearOutputBuffer.length;
4540
0
}
4541
4542
int wolfSSL_has_pending(const WOLFSSL* ssl)
4543
0
{
4544
0
    WOLFSSL_ENTER("wolfSSL_has_pending");
4545
0
    if (ssl == NULL)
4546
0
        return WOLFSSL_FAILURE;
4547
4548
0
    return ssl->buffers.clearOutputBuffer.length > 0;
4549
0
}
4550
4551
#ifndef WOLFSSL_LEANPSK
4552
/* turn on handshake group messages for context */
4553
int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
4554
0
{
4555
0
    if (ctx == NULL)
4556
0
       return BAD_FUNC_ARG;
4557
4558
0
    ctx->groupMessages = 1;
4559
4560
0
    return WOLFSSL_SUCCESS;
4561
0
}
4562
#endif
4563
4564
4565
#ifndef NO_WOLFSSL_CLIENT
4566
/* connect enough to get peer cert chain */
4567
int wolfSSL_connect_cert(WOLFSSL* ssl)
4568
0
{
4569
0
    int  ret;
4570
4571
0
    if (ssl == NULL)
4572
0
        return WOLFSSL_FAILURE;
4573
4574
0
    ssl->options.certOnly = 1;
4575
0
    ret = wolfSSL_connect(ssl);
4576
0
    ssl->options.certOnly   = 0;
4577
4578
0
    return ret;
4579
0
}
4580
#endif
4581
4582
4583
#ifndef WOLFSSL_LEANPSK
4584
/* turn on handshake group messages for ssl object */
4585
int wolfSSL_set_group_messages(WOLFSSL* ssl)
4586
0
{
4587
0
    if (ssl == NULL)
4588
0
       return BAD_FUNC_ARG;
4589
4590
0
    ssl->options.groupMessages = 1;
4591
4592
0
    return WOLFSSL_SUCCESS;
4593
0
}
4594
4595
4596
/* make minVersion the internal equivalent SSL version */
4597
static int SetMinVersionHelper(byte* minVersion, int version)
4598
0
{
4599
#ifdef NO_TLS
4600
    (void)minVersion;
4601
#endif
4602
4603
0
    switch (version) {
4604
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4605
        case WOLFSSL_SSLV3:
4606
            *minVersion = SSLv3_MINOR;
4607
            break;
4608
#endif
4609
4610
0
#ifndef NO_TLS
4611
0
    #ifndef NO_OLD_TLS
4612
        #ifdef WOLFSSL_ALLOW_TLSV10
4613
        case WOLFSSL_TLSV1:
4614
            *minVersion = TLSv1_MINOR;
4615
            break;
4616
        #endif
4617
4618
0
        case WOLFSSL_TLSV1_1:
4619
0
            *minVersion = TLSv1_1_MINOR;
4620
0
            break;
4621
0
    #endif
4622
0
    #ifndef WOLFSSL_NO_TLS12
4623
0
        case WOLFSSL_TLSV1_2:
4624
0
            *minVersion = TLSv1_2_MINOR;
4625
0
            break;
4626
0
    #endif
4627
0
#endif
4628
0
    #ifdef WOLFSSL_TLS13
4629
0
        case WOLFSSL_TLSV1_3:
4630
0
            *minVersion = TLSv1_3_MINOR;
4631
0
            break;
4632
0
    #endif
4633
4634
#ifdef WOLFSSL_DTLS
4635
        case WOLFSSL_DTLSV1:
4636
            *minVersion = DTLS_MINOR;
4637
            break;
4638
        case WOLFSSL_DTLSV1_2:
4639
            *minVersion = DTLSv1_2_MINOR;
4640
            break;
4641
#ifdef WOLFSSL_DTLS13
4642
        case WOLFSSL_DTLSV1_3:
4643
            *minVersion = DTLSv1_3_MINOR;
4644
            break;
4645
#endif /* WOLFSSL_DTLS13 */
4646
#endif /* WOLFSSL_DTLS */
4647
4648
0
        default:
4649
0
            WOLFSSL_MSG("Bad function argument");
4650
0
            return BAD_FUNC_ARG;
4651
0
    }
4652
4653
0
    return WOLFSSL_SUCCESS;
4654
0
}
4655
4656
4657
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
4658
WOLFSSL_ABI
4659
int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
4660
0
{
4661
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
4662
4663
0
    if (ctx == NULL) {
4664
0
        WOLFSSL_MSG("Bad function argument");
4665
0
        return BAD_FUNC_ARG;
4666
0
    }
4667
4668
0
    return SetMinVersionHelper(&ctx->minDowngrade, version);
4669
0
}
4670
4671
4672
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
4673
int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
4674
0
{
4675
0
    WOLFSSL_ENTER("wolfSSL_SetMinVersion");
4676
4677
0
    if (ssl == NULL) {
4678
0
        WOLFSSL_MSG("Bad function argument");
4679
0
        return BAD_FUNC_ARG;
4680
0
    }
4681
4682
0
    return SetMinVersionHelper(&ssl->options.minDowngrade, version);
4683
0
}
4684
4685
4686
/* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
4687
int wolfSSL_GetVersion(const WOLFSSL* ssl)
4688
0
{
4689
0
    if (ssl == NULL)
4690
0
        return BAD_FUNC_ARG;
4691
4692
0
    if (ssl->version.major == SSLv3_MAJOR) {
4693
0
        switch (ssl->version.minor) {
4694
0
            case SSLv3_MINOR :
4695
0
                return WOLFSSL_SSLV3;
4696
0
            case TLSv1_MINOR :
4697
0
                return WOLFSSL_TLSV1;
4698
0
            case TLSv1_1_MINOR :
4699
0
                return WOLFSSL_TLSV1_1;
4700
0
            case TLSv1_2_MINOR :
4701
0
                return WOLFSSL_TLSV1_2;
4702
0
            case TLSv1_3_MINOR :
4703
0
                return WOLFSSL_TLSV1_3;
4704
0
            default:
4705
0
                break;
4706
0
        }
4707
0
    }
4708
4709
0
    return VERSION_ERROR;
4710
0
}
4711
4712
int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
4713
0
{
4714
0
    word16 haveRSA = 1;
4715
0
    word16 havePSK = 0;
4716
0
    int    keySz   = 0;
4717
4718
0
    WOLFSSL_ENTER("wolfSSL_SetVersion");
4719
4720
0
    if (ssl == NULL) {
4721
0
        WOLFSSL_MSG("Bad function argument");
4722
0
        return BAD_FUNC_ARG;
4723
0
    }
4724
4725
0
    switch (version) {
4726
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4727
        case WOLFSSL_SSLV3:
4728
            ssl->version = MakeSSLv3();
4729
            break;
4730
#endif
4731
4732
0
#ifndef NO_TLS
4733
0
    #ifndef NO_OLD_TLS
4734
        #ifdef WOLFSSL_ALLOW_TLSV10
4735
        case WOLFSSL_TLSV1:
4736
            ssl->version = MakeTLSv1();
4737
            break;
4738
        #endif
4739
4740
0
        case WOLFSSL_TLSV1_1:
4741
0
            ssl->version = MakeTLSv1_1();
4742
0
            break;
4743
0
    #endif
4744
0
    #ifndef WOLFSSL_NO_TLS12
4745
0
        case WOLFSSL_TLSV1_2:
4746
0
            ssl->version = MakeTLSv1_2();
4747
0
            break;
4748
0
    #endif
4749
4750
0
    #ifdef WOLFSSL_TLS13
4751
0
        case WOLFSSL_TLSV1_3:
4752
0
            ssl->version = MakeTLSv1_3();
4753
0
            break;
4754
0
    #endif /* WOLFSSL_TLS13 */
4755
0
#endif
4756
4757
0
        default:
4758
0
            WOLFSSL_MSG("Bad function argument");
4759
0
            return BAD_FUNC_ARG;
4760
0
    }
4761
4762
    #ifdef NO_RSA
4763
        haveRSA = 0;
4764
    #endif
4765
    #ifndef NO_PSK
4766
        havePSK = ssl->options.havePSK;
4767
    #endif
4768
0
    #ifndef NO_CERTS
4769
0
        keySz = ssl->buffers.keySz;
4770
0
    #endif
4771
4772
0
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
4773
0
               ssl->options.haveDH, ssl->options.haveECDSAsig,
4774
0
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
4775
0
               ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
4776
0
               ssl->options.haveAnon, TRUE, ssl->options.side);
4777
0
    return WOLFSSL_SUCCESS;
4778
0
}
4779
#endif /* !leanpsk */
4780
4781
#ifndef NO_CERTS
4782
4783
/* hash is the SHA digest of name, just use first 32 bits as hash */
4784
static WC_INLINE word32 HashSigner(const byte* hash)
4785
0
{
4786
0
    return MakeWordFromHash(hash) % CA_TABLE_SIZE;
4787
0
}
4788
4789
4790
/* does CA already exist on signer list */
4791
int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash)
4792
0
{
4793
0
    Signer* signers;
4794
0
    int     ret = 0;
4795
0
    word32  row;
4796
4797
0
    if (cm == NULL || hash == NULL) {
4798
0
        return ret;
4799
0
    }
4800
4801
0
    row = HashSigner(hash);
4802
4803
0
    if (wc_LockMutex(&cm->caLock) != 0) {
4804
0
        return ret;
4805
0
    }
4806
0
    signers = cm->caTable[row];
4807
0
    while (signers) {
4808
0
        byte* subjectHash;
4809
4810
0
    #ifndef NO_SKID
4811
0
        subjectHash = signers->subjectKeyIdHash;
4812
    #else
4813
        subjectHash = signers->subjectNameHash;
4814
    #endif
4815
4816
0
        if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
4817
0
            ret = 1; /* success */
4818
0
            break;
4819
0
        }
4820
0
        signers = signers->next;
4821
0
    }
4822
0
    wc_UnLockMutex(&cm->caLock);
4823
4824
0
    return ret;
4825
0
}
4826
4827
4828
#ifdef WOLFSSL_TRUST_PEER_CERT
4829
/* hash is the SHA digest of name, just use first 32 bits as hash */
4830
static WC_INLINE word32 TrustedPeerHashSigner(const byte* hash)
4831
{
4832
    return MakeWordFromHash(hash) % TP_TABLE_SIZE;
4833
}
4834
4835
/* does trusted peer already exist on signer list */
4836
int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert)
4837
{
4838
    TrustedPeerCert* tp;
4839
    int     ret = 0;
4840
    word32  row = TrustedPeerHashSigner(cert->subjectHash);
4841
4842
    if (wc_LockMutex(&cm->tpLock) != 0)
4843
        return  ret;
4844
    tp = cm->tpTable[row];
4845
    while (tp) {
4846
        if (XMEMCMP(cert->subjectHash, tp->subjectNameHash,
4847
                SIGNER_DIGEST_SIZE) == 0)
4848
            ret = 1;
4849
    #ifndef NO_SKID
4850
        if (cert->extSubjKeyIdSet) {
4851
            /* Compare SKID as well if available */
4852
            if (ret == 1 && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
4853
                    SIGNER_DIGEST_SIZE) != 0)
4854
                ret = 0;
4855
        }
4856
    #endif
4857
        if (ret == 1)
4858
            break;
4859
        tp = tp->next;
4860
    }
4861
    wc_UnLockMutex(&cm->tpLock);
4862
4863
    return ret;
4864
}
4865
4866
4867
/* return Trusted Peer if found, otherwise NULL
4868
    type is what to match on
4869
 */
4870
TrustedPeerCert* GetTrustedPeer(void* vp, DecodedCert* cert)
4871
{
4872
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
4873
    TrustedPeerCert* ret = NULL;
4874
    TrustedPeerCert* tp  = NULL;
4875
    word32  row;
4876
4877
    if (cm == NULL || cert == NULL)
4878
        return NULL;
4879
4880
    row = TrustedPeerHashSigner(cert->subjectHash);
4881
4882
    if (wc_LockMutex(&cm->tpLock) != 0)
4883
        return ret;
4884
4885
    tp = cm->tpTable[row];
4886
    while (tp) {
4887
        if (XMEMCMP(cert->subjectHash, tp->subjectNameHash,
4888
                SIGNER_DIGEST_SIZE) == 0)
4889
            ret = tp;
4890
    #ifndef NO_SKID
4891
        if (cert->extSubjKeyIdSet) {
4892
            /* Compare SKID as well if available */
4893
            if (ret != NULL && XMEMCMP(cert->extSubjKeyId, tp->subjectKeyIdHash,
4894
                    SIGNER_DIGEST_SIZE) != 0)
4895
                ret = NULL;
4896
        }
4897
    #endif
4898
        if (ret != NULL)
4899
            break;
4900
        tp = tp->next;
4901
    }
4902
    wc_UnLockMutex(&cm->tpLock);
4903
4904
    return ret;
4905
}
4906
4907
4908
int MatchTrustedPeer(TrustedPeerCert* tp, DecodedCert* cert)
4909
{
4910
    if (tp == NULL || cert == NULL)
4911
        return BAD_FUNC_ARG;
4912
4913
    /* subject key id or subject hash has been compared when searching
4914
       tpTable for the cert from function GetTrustedPeer */
4915
4916
    /* compare signatures */
4917
    if (tp->sigLen == cert->sigLength) {
4918
        if (XMEMCMP(tp->sig, cert->signature, cert->sigLength)) {
4919
            return WOLFSSL_FAILURE;
4920
        }
4921
    }
4922
    else {
4923
        return WOLFSSL_FAILURE;
4924
    }
4925
4926
    return WOLFSSL_SUCCESS;
4927
}
4928
#endif /* WOLFSSL_TRUST_PEER_CERT */
4929
4930
4931
/* return CA if found, otherwise NULL */
4932
Signer* GetCA(void* vp, byte* hash)
4933
0
{
4934
0
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
4935
0
    Signer* ret = NULL;
4936
0
    Signer* signers;
4937
0
    word32  row = 0;
4938
4939
0
    if (cm == NULL || hash == NULL)
4940
0
        return NULL;
4941
4942
0
    row = HashSigner(hash);
4943
4944
0
    if (wc_LockMutex(&cm->caLock) != 0)
4945
0
        return ret;
4946
4947
0
    signers = cm->caTable[row];
4948
0
    while (signers) {
4949
0
        byte* subjectHash;
4950
0
        #ifndef NO_SKID
4951
0
            subjectHash = signers->subjectKeyIdHash;
4952
        #else
4953
            subjectHash = signers->subjectNameHash;
4954
        #endif
4955
0
        if (XMEMCMP(hash, subjectHash, SIGNER_DIGEST_SIZE) == 0) {
4956
0
            ret = signers;
4957
0
            break;
4958
0
        }
4959
0
        signers = signers->next;
4960
0
    }
4961
0
    wc_UnLockMutex(&cm->caLock);
4962
4963
0
    return ret;
4964
0
}
4965
4966
4967
#ifndef NO_SKID
4968
/* return CA if found, otherwise NULL. Walk through hash table. */
4969
Signer* GetCAByName(void* vp, byte* hash)
4970
0
{
4971
0
    WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp;
4972
0
    Signer* ret = NULL;
4973
0
    Signer* signers;
4974
0
    word32  row;
4975
4976
0
    if (cm == NULL)
4977
0
        return NULL;
4978
4979
0
    if (wc_LockMutex(&cm->caLock) != 0)
4980
0
        return ret;
4981
4982
0
    for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) {
4983
0
        signers = cm->caTable[row];
4984
0
        while (signers && ret == NULL) {
4985
0
            if (XMEMCMP(hash, signers->subjectNameHash,
4986
0
                        SIGNER_DIGEST_SIZE) == 0) {
4987
0
                ret = signers;
4988
0
            }
4989
0
            signers = signers->next;
4990
0
        }
4991
0
    }
4992
0
    wc_UnLockMutex(&cm->caLock);
4993
4994
0
    return ret;
4995
0
}
4996
#endif
4997
4998
4999
#ifdef WOLFSSL_TRUST_PEER_CERT
5000
/* add a trusted peer cert to linked list */
5001
int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify)
5002
{
5003
    int ret, row;
5004
    TrustedPeerCert* peerCert;
5005
    DecodedCert* cert;
5006
    DerBuffer*   der = *pDer;
5007
5008
    WOLFSSL_MSG("Adding a Trusted Peer Cert");
5009
5010
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cm->heap,
5011
                                 DYNAMIC_TYPE_DCERT);
5012
    if (cert == NULL) {
5013
        FreeDer(&der);
5014
        return MEMORY_E;
5015
    }
5016
5017
    InitDecodedCert(cert, der->buffer, der->length, cm->heap);
5018
    if ((ret = ParseCert(cert, TRUSTED_PEER_TYPE, verify, cm)) != 0) {
5019
        FreeDecodedCert(cert);
5020
        XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
5021
        FreeDer(&der);
5022
        return ret;
5023
    }
5024
    WOLFSSL_MSG("\tParsed new trusted peer cert");
5025
5026
    peerCert = (TrustedPeerCert*)XMALLOC(sizeof(TrustedPeerCert), cm->heap,
5027
                                                             DYNAMIC_TYPE_CERT);
5028
    if (peerCert == NULL) {
5029
        FreeDecodedCert(cert);
5030
        XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5031
        FreeDer(&der);
5032
        return MEMORY_E;
5033
    }
5034
    XMEMSET(peerCert, 0, sizeof(TrustedPeerCert));
5035
5036
    #ifndef IGNORE_NAME_CONSTRAINTS
5037
        if (peerCert->permittedNames)
5038
            FreeNameSubtrees(peerCert->permittedNames, cm->heap);
5039
        if (peerCert->excludedNames)
5040
            FreeNameSubtrees(peerCert->excludedNames, cm->heap);
5041
    #endif
5042
5043
    if (AlreadyTrustedPeer(cm, cert)) {
5044
        WOLFSSL_MSG("\tAlready have this CA, not adding again");
5045
        FreeTrustedPeer(peerCert, cm->heap);
5046
        (void)ret;
5047
    }
5048
    else {
5049
        /* add trusted peer signature */
5050
        peerCert->sigLen = cert->sigLength;
5051
        peerCert->sig = (byte *)XMALLOC(cert->sigLength, cm->heap,
5052
                                                        DYNAMIC_TYPE_SIGNATURE);
5053
        if (peerCert->sig == NULL) {
5054
            FreeDecodedCert(cert);
5055
            XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5056
            FreeTrustedPeer(peerCert, cm->heap);
5057
            FreeDer(&der);
5058
            return MEMORY_E;
5059
        }
5060
        XMEMCPY(peerCert->sig, cert->signature, cert->sigLength);
5061
5062
        /* add trusted peer name */
5063
        peerCert->nameLen = cert->subjectCNLen;
5064
        peerCert->name    = cert->subjectCN;
5065
        #ifndef IGNORE_NAME_CONSTRAINTS
5066
            peerCert->permittedNames = cert->permittedNames;
5067
            peerCert->excludedNames  = cert->excludedNames;
5068
        #endif
5069
5070
        /* add SKID when available and hash of name */
5071
        #ifndef NO_SKID
5072
            XMEMCPY(peerCert->subjectKeyIdHash, cert->extSubjKeyId,
5073
                    SIGNER_DIGEST_SIZE);
5074
        #endif
5075
            XMEMCPY(peerCert->subjectNameHash, cert->subjectHash,
5076
                    SIGNER_DIGEST_SIZE);
5077
            peerCert->next    = NULL; /* If Key Usage not set, all uses valid. */
5078
            cert->subjectCN = 0;
5079
        #ifndef IGNORE_NAME_CONSTRAINTS
5080
            cert->permittedNames = NULL;
5081
            cert->excludedNames = NULL;
5082
        #endif
5083
5084
            row = TrustedPeerHashSigner(peerCert->subjectNameHash);
5085
5086
            if (wc_LockMutex(&cm->tpLock) == 0) {
5087
                peerCert->next = cm->tpTable[row];
5088
                cm->tpTable[row] = peerCert;   /* takes ownership */
5089
                wc_UnLockMutex(&cm->tpLock);
5090
            }
5091
            else {
5092
                WOLFSSL_MSG("\tTrusted Peer Cert Mutex Lock failed");
5093
                FreeDecodedCert(cert);
5094
                XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5095
                FreeTrustedPeer(peerCert, cm->heap);
5096
                FreeDer(&der);
5097
                return BAD_MUTEX_E;
5098
            }
5099
        }
5100
5101
    WOLFSSL_MSG("\tFreeing parsed trusted peer cert");
5102
    FreeDecodedCert(cert);
5103
    XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT);
5104
    WOLFSSL_MSG("\tFreeing der trusted peer cert");
5105
    FreeDer(&der);
5106
    WOLFSSL_MSG("\t\tOK Freeing der trusted peer cert");
5107
    WOLFSSL_LEAVE("AddTrustedPeer", ret);
5108
5109
    return WOLFSSL_SUCCESS;
5110
}
5111
#endif /* WOLFSSL_TRUST_PEER_CERT */
5112
5113
5114
/* owns der, internal now uses too */
5115
/* type flag ids from user or from chain received during verify
5116
   don't allow chain ones to be added w/o isCA extension */
5117
int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify)
5118
0
{
5119
0
    int         ret;
5120
0
    Signer*     signer = NULL;
5121
0
    word32      row;
5122
0
    byte*       subjectHash;
5123
0
#ifdef WOLFSSL_SMALL_STACK
5124
0
    DecodedCert* cert = NULL;
5125
#else
5126
    DecodedCert  cert[1];
5127
#endif
5128
0
    DerBuffer*   der = *pDer;
5129
5130
0
    WOLFSSL_MSG("Adding a CA");
5131
5132
0
    if (cm == NULL) {
5133
0
        FreeDer(pDer);
5134
0
        return BAD_FUNC_ARG;
5135
0
    }
5136
5137
0
#ifdef WOLFSSL_SMALL_STACK
5138
0
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
5139
0
                                 DYNAMIC_TYPE_DCERT);
5140
0
    if (cert == NULL) {
5141
0
        FreeDer(pDer);
5142
0
        return MEMORY_E;
5143
0
    }
5144
0
#endif
5145
5146
0
    InitDecodedCert(cert, der->buffer, der->length, cm->heap);
5147
0
    ret = ParseCert(cert, CA_TYPE, verify, cm);
5148
0
    WOLFSSL_MSG("\tParsed new CA");
5149
5150
0
#ifndef NO_SKID
5151
0
    subjectHash = cert->extSubjKeyId;
5152
#else
5153
    subjectHash = cert->subjectHash;
5154
#endif
5155
5156
    /* check CA key size */
5157
0
    if (verify) {
5158
0
        switch (cert->keyOID) {
5159
0
        #ifndef NO_RSA
5160
0
            #ifdef WC_RSA_PSS
5161
0
            case RSAPSSk:
5162
0
            #endif
5163
0
            case RSAk:
5164
0
                if (cm->minRsaKeySz < 0 ||
5165
0
                                   cert->pubKeySize < (word16)cm->minRsaKeySz) {
5166
0
                    ret = RSA_KEY_SIZE_E;
5167
0
                    WOLFSSL_MSG("\tCA RSA key size error");
5168
0
                }
5169
0
                break;
5170
0
        #endif /* !NO_RSA */
5171
0
            #ifdef HAVE_ECC
5172
0
            case ECDSAk:
5173
0
                if (cm->minEccKeySz < 0 ||
5174
0
                                   cert->pubKeySize < (word16)cm->minEccKeySz) {
5175
0
                    ret = ECC_KEY_SIZE_E;
5176
0
                    WOLFSSL_MSG("\tCA ECC key size error");
5177
0
                }
5178
0
                break;
5179
0
            #endif /* HAVE_ECC */
5180
0
            #ifdef HAVE_ED25519
5181
0
            case ED25519k:
5182
0
                if (cm->minEccKeySz < 0 ||
5183
0
                                   ED25519_KEY_SIZE < (word16)cm->minEccKeySz) {
5184
0
                    ret = ECC_KEY_SIZE_E;
5185
0
                    WOLFSSL_MSG("\tCA ECC key size error");
5186
0
                }
5187
0
                break;
5188
0
            #endif /* HAVE_ED25519 */
5189
0
            #ifdef HAVE_ED448
5190
0
            case ED448k:
5191
0
                if (cm->minEccKeySz < 0 ||
5192
0
                                     ED448_KEY_SIZE < (word16)cm->minEccKeySz) {
5193
0
                    ret = ECC_KEY_SIZE_E;
5194
0
                    WOLFSSL_MSG("\tCA ECC key size error");
5195
0
                }
5196
0
                break;
5197
0
            #endif /* HAVE_ED448 */
5198
            #if defined(HAVE_PQC)
5199
            #if defined(HAVE_FALCON)
5200
            case FALCON_LEVEL1k:
5201
                if (cm->minFalconKeySz < 0 ||
5202
                          FALCON_LEVEL1_KEY_SIZE < (word16)cm->minFalconKeySz) {
5203
                    ret = FALCON_KEY_SIZE_E;
5204
                    WOLFSSL_MSG("\tCA Falcon level 1 key size error");
5205
                }
5206
                break;
5207
            case FALCON_LEVEL5k:
5208
                if (cm->minFalconKeySz < 0 ||
5209
                          FALCON_LEVEL5_KEY_SIZE < (word16)cm->minFalconKeySz) {
5210
                    ret = FALCON_KEY_SIZE_E;
5211
                    WOLFSSL_MSG("\tCA Falcon level 5 key size error");
5212
                }
5213
                break;
5214
            #endif /* HAVE_FALCON */
5215
            #if defined(HAVE_DILITHIUM)
5216
            case DILITHIUM_LEVEL2k:
5217
            case DILITHIUM_AES_LEVEL2k:
5218
                if (cm->minDilithiumKeySz < 0 ||
5219
                    DILITHIUM_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
5220
                    ret = DILITHIUM_KEY_SIZE_E;
5221
                    WOLFSSL_MSG("\tCA Dilithium level 2 key size error");
5222
                }
5223
                break;
5224
            case DILITHIUM_LEVEL3k:
5225
            case DILITHIUM_AES_LEVEL3k:
5226
                if (cm->minDilithiumKeySz < 0 ||
5227
                    DILITHIUM_LEVEL3_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
5228
                    ret = DILITHIUM_KEY_SIZE_E;
5229
                    WOLFSSL_MSG("\tCA Dilithium level 3 key size error");
5230
                }
5231
                break;
5232
            case DILITHIUM_LEVEL5k:
5233
            case DILITHIUM_AES_LEVEL5k:
5234
                if (cm->minDilithiumKeySz < 0 ||
5235
                    DILITHIUM_LEVEL5_KEY_SIZE < (word16)cm->minDilithiumKeySz) {
5236
                    ret = DILITHIUM_KEY_SIZE_E;
5237
                    WOLFSSL_MSG("\tCA Dilithium level 5 key size error");
5238
                }
5239
                break;
5240
            #endif /* HAVE_DILITHIUM */
5241
            #endif /* HAVE_PQC */
5242
5243
0
            default:
5244
0
                WOLFSSL_MSG("\tNo key size check done on CA");
5245
0
                break; /* no size check if key type is not in switch */
5246
0
        }
5247
0
    }
5248
5249
0
    if (ret == 0 && cert->isCA == 0 && type != WOLFSSL_USER_CA) {
5250
0
        WOLFSSL_MSG("\tCan't add as CA if not actually one");
5251
0
        ret = NOT_CA_ERROR;
5252
0
    }
5253
0
#ifndef ALLOW_INVALID_CERTSIGN
5254
0
    else if (ret == 0 && cert->isCA == 1 && type != WOLFSSL_USER_CA &&
5255
0
        !cert->selfSigned && (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0) {
5256
        /* Intermediate CA certs are required to have the keyCertSign
5257
        * extension set. User loaded root certs are not. */
5258
0
        WOLFSSL_MSG("\tDoesn't have key usage certificate signing");
5259
0
        ret = NOT_CA_ERROR;
5260
0
    }
5261
0
#endif
5262
0
    else if (ret == 0 && AlreadySigner(cm, subjectHash)) {
5263
0
        WOLFSSL_MSG("\tAlready have this CA, not adding again");
5264
0
        (void)ret;
5265
0
    }
5266
0
    else if (ret == 0) {
5267
        /* take over signer parts */
5268
0
        signer = MakeSigner(cm->heap);
5269
0
        if (!signer)
5270
0
            ret = MEMORY_ERROR;
5271
0
    }
5272
0
    if (ret == 0 && signer != NULL) {
5273
    #ifdef WOLFSSL_SIGNER_DER_CERT
5274
        ret = AllocDer(&signer->derCert, der->length, der->type, NULL);
5275
    }
5276
    if (ret == 0 && signer != NULL) {
5277
        XMEMCPY(signer->derCert->buffer, der->buffer, der->length);
5278
    #endif
5279
0
        signer->keyOID         = cert->keyOID;
5280
0
        if (cert->pubKeyStored) {
5281
0
            signer->publicKey      = cert->publicKey;
5282
0
            signer->pubKeySize     = cert->pubKeySize;
5283
0
        }
5284
0
        if (cert->subjectCNStored) {
5285
0
            signer->nameLen        = cert->subjectCNLen;
5286
0
            signer->name           = cert->subjectCN;
5287
0
        }
5288
0
        signer->pathLength     = cert->pathLength;
5289
0
        signer->maxPathLen     = cert->maxPathLen;
5290
0
        signer->pathLengthSet  = cert->pathLengthSet;
5291
0
        signer->selfSigned     = cert->selfSigned;
5292
0
    #ifndef IGNORE_NAME_CONSTRAINTS
5293
0
        signer->permittedNames = cert->permittedNames;
5294
0
        signer->excludedNames  = cert->excludedNames;
5295
0
    #endif
5296
0
    #ifndef NO_SKID
5297
0
        XMEMCPY(signer->subjectKeyIdHash, cert->extSubjKeyId,
5298
0
                SIGNER_DIGEST_SIZE);
5299
0
    #endif
5300
0
        XMEMCPY(signer->subjectNameHash, cert->subjectHash,
5301
0
                SIGNER_DIGEST_SIZE);
5302
    #ifdef HAVE_OCSP
5303
        XMEMCPY(signer->subjectKeyHash, cert->subjectKeyHash,
5304
                KEYID_SIZE);
5305
    #endif
5306
0
        signer->keyUsage = cert->extKeyUsageSet ? cert->extKeyUsage
5307
0
                                                : 0xFFFF;
5308
0
        signer->next    = NULL; /* If Key Usage not set, all uses valid. */
5309
0
        cert->publicKey = 0;    /* in case lock fails don't free here.   */
5310
0
        cert->subjectCN = 0;
5311
0
    #ifndef IGNORE_NAME_CONSTRAINTS
5312
0
        cert->permittedNames = NULL;
5313
0
        cert->excludedNames = NULL;
5314
0
    #endif
5315
5316
0
    #ifndef NO_SKID
5317
0
        row = HashSigner(signer->subjectKeyIdHash);
5318
    #else
5319
        row = HashSigner(signer->subjectNameHash);
5320
    #endif
5321
5322
0
        if (wc_LockMutex(&cm->caLock) == 0) {
5323
0
            signer->next = cm->caTable[row];
5324
0
            cm->caTable[row] = signer;   /* takes ownership */
5325
0
            wc_UnLockMutex(&cm->caLock);
5326
0
            if (cm->caCacheCallback)
5327
0
                cm->caCacheCallback(der->buffer, (int)der->length, type);
5328
0
        }
5329
0
        else {
5330
0
            WOLFSSL_MSG("\tCA Mutex Lock failed");
5331
0
            ret = BAD_MUTEX_E;
5332
0
            FreeSigner(signer, cm->heap);
5333
0
        }
5334
0
    }
5335
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
5336
    /* Verify CA by TSIP so that generated tsip key is going to be able to */
5337
    /* be used for peer's cert verification                                */
5338
    /* TSIP is only able to handle USER CA, and only one CA.               */
5339
    /* Therefore, it doesn't need to call TSIP again if there is already   */
5340
    /* verified CA.                                                        */
5341
    if ( ret == 0 && signer != NULL ) {
5342
        signer->cm_idx = row;
5343
        if (type == WOLFSSL_USER_CA) {
5344
            if ((ret = wc_Renesas_cmn_RootCertVerify(cert->source, cert->maxIdx,
5345
                 cert->sigCtx.CertAtt.pubkey_n_start,
5346
                 cert->sigCtx.CertAtt.pubkey_n_len - 1,
5347
                 cert->sigCtx.CertAtt.pubkey_e_start,
5348
                cert->sigCtx.CertAtt.pubkey_e_len - 1,
5349
                 row/* cm index */))
5350
                < 0)
5351
                WOLFSSL_MSG("Renesas_RootCertVerify() failed");
5352
            else
5353
                WOLFSSL_MSG("Renesas_RootCertVerify() succeed or skipped");
5354
        }
5355
    }
5356
#endif /* TSIP or SCE */
5357
5358
0
    WOLFSSL_MSG("\tFreeing Parsed CA");
5359
0
    FreeDecodedCert(cert);
5360
0
#ifdef WOLFSSL_SMALL_STACK
5361
0
    XFREE(cert, NULL, DYNAMIC_TYPE_DCERT);
5362
0
#endif
5363
0
    WOLFSSL_MSG("\tFreeing der CA");
5364
0
    FreeDer(pDer);
5365
0
    WOLFSSL_MSG("\t\tOK Freeing der CA");
5366
5367
0
    WOLFSSL_LEAVE("AddCA", ret);
5368
5369
0
    return ret == 0 ? WOLFSSL_SUCCESS : ret;
5370
0
}
5371
5372
#endif /* !NO_CERTS */
5373
5374
5375
#ifndef NO_SESSION_CACHE
5376
5377
    /* basic config gives a cache with 33 sessions, adequate for clients and
5378
       embedded servers
5379