Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-sp-math/src/ssl_sess.c
Line
Count
Source
1
/* ssl_sess.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if !defined(WOLFSSL_SSL_SESS_INCLUDED)
25
    #ifndef WOLFSSL_IGNORE_FILE_WARN
26
        #warning ssl_sess.c does not need to be compiled separately from ssl.c
27
    #endif
28
#else
29
30
#ifndef NO_SESSION_CACHE
31
    #include <wolfssl/ssl_sess.h>
32
33
    static WC_THREADSHARED SessionRow SessionCache[SESSION_ROWS];
34
35
    #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS)
36
        static WC_THREADSHARED word32 PeakSessions;
37
    #endif
38
39
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
40
    #define SESSION_ROW_RD_LOCK(row)   wc_LockRwLock_Rd(&(row)->row_lock)
41
    #define SESSION_ROW_WR_LOCK(row)   wc_LockRwLock_Wr(&(row)->row_lock)
42
    #define SESSION_ROW_UNLOCK(row)    wc_UnLockRwLock(&(row)->row_lock);
43
    #else
44
    static WC_THREADSHARED wolfSSL_RwLock session_lock; /* SessionCache lock */
45
    static WC_THREADSHARED int session_lock_valid = 0;
46
183
    #define SESSION_ROW_RD_LOCK(row)   wc_LockRwLock_Rd(&session_lock)
47
75
    #define SESSION_ROW_WR_LOCK(row)   wc_LockRwLock_Wr(&session_lock)
48
258
    #define SESSION_ROW_UNLOCK(row)    wc_UnLockRwLock(&session_lock);
49
    #endif
50
51
    #if !defined(NO_SESSION_CACHE_REF) && defined(NO_CLIENT_CACHE)
52
        #error ClientCache is required when not using NO_SESSION_CACHE_REF
53
    #endif
54
55
    #if !defined(NO_SESSION_CACHE_REF) && \
56
        !defined(WOLFSSL_SESSION_CACHE_REF_WARNED)
57
        #if !defined(_MSC_VER) && !defined(__TASKING__)
58
            #warning WOLFSSL_SESSION_CACHE_REF selects the deprecated wolfSSL_get_session() session cache reference, use wolfSSL_get1_session() instead, or define WOLFSSL_SESSION_CACHE_REF_WARNED to silence this
59
        #else
60
            #pragma message("Warning: WOLFSSL_SESSION_CACHE_REF selects the deprecated wolfSSL_get_session() session cache reference, use wolfSSL_get1_session() instead, or define WOLFSSL_SESSION_CACHE_REF_WARNED to silence this")
61
        #endif
62
    #endif
63
64
    #ifndef NO_CLIENT_CACHE
65
        static WC_THREADSHARED ClientRow ClientCache[CLIENT_SESSION_ROWS];
66
                                                     /* Client Cache */
67
                                                     /* uses session mutex */
68
        /* ClientCache mutex */
69
        static WC_THREADSHARED wolfSSL_Mutex clisession_mutex
70
            WOLFSSL_MUTEX_INITIALIZER_CLAUSE(clisession_mutex);
71
        #ifndef WOLFSSL_MUTEX_INITIALIZER
72
        static WC_THREADSHARED int clisession_mutex_valid = 0;
73
        #endif
74
    #endif /* !NO_CLIENT_CACHE */
75
76
    /* Resolve a client cache reference and keep its row read-locked. */
77
    static WOLFSSL_SESSION* ClientSessionToSessionRdLocked(
78
        const WOLFSSL_SESSION* session, SessionRow** lockedRow);
79
80
    void EvictSessionFromCache(WOLFSSL_SESSION* session)
81
202k
    {
82
    #ifdef HAVE_EX_DATA
83
        byte save_ownExData = session->ownExData;
84
        session->ownExData = 1; /* Make sure ex_data access doesn't lead back
85
                                 * into the cache. */
86
    #endif /* HAVE_EX_DATA */
87
    #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
88
        if (session->rem_sess_cb != NULL) {
89
            session->rem_sess_cb(NULL, session);
90
            session->rem_sess_cb = NULL;
91
        }
92
    #endif /* HAVE_EXT_CACHE || HAVE_EX_DATA */
93
202k
        ForceZero(session->masterSecret, SECRET_LEN);
94
202k
        XMEMSET(session->sessionID, 0, ID_LEN);
95
202k
        session->sessionIDSz = 0;
96
    #ifdef HAVE_SESSION_TICKET
97
        if (session->ticketLenAlloc > 0) {
98
            XFREE(session->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK);
99
            session->ticket = session->staticTicket;
100
            session->ticketLen = 0;
101
            session->ticketLenAlloc = 0;
102
        }
103
    #endif /* HAVE_SESSION_TICKET */
104
    #ifdef HAVE_EX_DATA
105
        session->ownExData = save_ownExData;
106
    #endif /* HAVE_EX_DATA */
107
108
#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) &&                  \
109
    defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
110
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
111
        if ((session->ticketNonce.data != NULL) &&
112
            (session->ticketNonce.data != session->ticketNonce.dataStatic))
113
        {
114
            XFREE(session->ticketNonce.data, NULL, DYNAMIC_TYPE_SESSION_TICK);
115
            session->ticketNonce.data = NULL;
116
        }
117
#endif
118
202k
    }
119
120
WOLFSSL_ABI
121
WOLFSSL_SESSION* wolfSSL_get_session(WOLFSSL* ssl)
122
0
{
123
0
    WOLFSSL_ENTER("wolfSSL_get_session");
124
0
    if (ssl) {
125
0
#ifdef NO_SESSION_CACHE_REF
126
0
        return ssl->session;
127
#else
128
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
129
            /* On the client side we want to return a persistent reference for
130
             * backwards compatibility. */
131
#ifndef NO_CLIENT_CACHE
132
            if (ssl->clientSession) {
133
                return (WOLFSSL_SESSION*)ssl->clientSession;
134
            }
135
            else {
136
                /* Try to add a ClientCache entry to associate with the current
137
                 * session. Ignore any session cache options. */
138
                int err;
139
                const byte* id = ssl->session->sessionID;
140
                byte idSz = ssl->session->sessionIDSz;
141
                if (ssl->session->haveAltSessionID) {
142
                    id = ssl->session->altSessionID;
143
                    idSz = ID_LEN;
144
                }
145
                err = AddSessionToCache(ssl->ctx, ssl->session, id, idSz,
146
                        NULL, ssl->session->side,
147
                #ifdef HAVE_SESSION_TICKET
148
                        ssl->session->ticketLen > 0,
149
                #else
150
                        0,
151
                #endif
152
                        &ssl->clientSession);
153
                if (err == 0) {
154
                    return (WOLFSSL_SESSION*)ssl->clientSession;
155
                }
156
            }
157
#endif
158
        }
159
        else {
160
            return ssl->session;
161
        }
162
#endif
163
0
    }
164
165
0
    return NULL;
166
0
}
167
168
/* The get1 version requires caller to call SSL_SESSION_free */
169
WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl)
170
0
{
171
0
    WOLFSSL_SESSION* sess = NULL;
172
0
    WOLFSSL_ENTER("wolfSSL_get1_session");
173
0
    if (ssl != NULL) {
174
0
        sess = ssl->session;
175
0
        if (sess != NULL) {
176
            /* increase reference count if allocated session */
177
0
            if (sess->type == WOLFSSL_SESSION_TYPE_HEAP) {
178
0
                if (wolfSSL_SESSION_up_ref(sess) != WOLFSSL_SUCCESS)
179
0
                    sess = NULL;
180
0
            }
181
0
        }
182
0
    }
183
0
    return sess;
184
0
}
185
186
/* session is a private struct, return if it is setup or not */
187
int wolfSSL_SessionIsSetup(WOLFSSL_SESSION* session)
188
0
{
189
0
    SessionRow* sessRow = NULL;
190
0
    int ret = 0;
191
192
0
    session = ClientSessionToSessionRdLocked(session, &sessRow);
193
0
    if (session != NULL)
194
0
        ret = session->isSetup;
195
0
    if (sessRow != NULL) {
196
0
        SESSION_ROW_UNLOCK(sessRow);
197
0
    }
198
199
0
    return ret;
200
0
}
201
202
/*
203
 * Sets the session object to use when establishing a TLS/SSL session using
204
 * the ssl object. Therefore, this function must be called before
205
 * wolfSSL_connect. The session object to use can be obtained in a previous
206
 * TLS/SSL connection using wolfSSL_get_session.
207
 *
208
 * This function rejects the session if it has been expired when this function
209
 * is called. Note that this expiration check is wolfSSL specific and differs
210
 * from OpenSSL return code behavior.
211
 *
212
 * By default, wolfSSL_set_session returns WOLFSSL_SUCCESS on successfully
213
 * setting the session, WOLFSSL_FAILURE on failure due to the session cache
214
 * being disabled, or the session has expired.
215
 *
216
 * To match OpenSSL return code behavior when session is expired, define
217
 * OPENSSL_EXTRA and WOLFSSL_ERROR_CODE_OPENSSL. This behavior will return
218
 * WOLFSSL_SUCCESS even when the session is expired and rejected.
219
 */
220
WOLFSSL_ABI
221
int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* session)
222
0
{
223
0
    WOLFSSL_ENTER("wolfSSL_set_session");
224
0
    if (session)
225
0
        return wolfSSL_SetSession(ssl, session);
226
227
0
    return WOLFSSL_FAILURE;
228
0
}
229
230
231
#ifndef NO_CLIENT_CACHE
232
233
/* Associate client session with serverID, find existing or store for saving
234
   if newSession flag on, don't reuse existing session
235
   WOLFSSL_SUCCESS on ok */
236
int wolfSSL_SetServerID(WOLFSSL* ssl, const byte* id, int len, int newSession)
237
0
{
238
0
    WOLFSSL_SESSION* session = NULL;
239
0
    byte idHash[SERVER_ID_LEN];
240
241
0
    WOLFSSL_ENTER("wolfSSL_SetServerID");
242
243
0
    if (ssl == NULL || id == NULL || len <= 0)
244
0
        return BAD_FUNC_ARG;
245
246
0
    if (len > SERVER_ID_LEN) {
247
#if defined(NO_SHA) && !defined(NO_SHA256)
248
        if (wc_Sha256Hash(id, len, idHash) != 0)
249
            return WOLFSSL_FAILURE;
250
#else
251
0
        if (wc_ShaHash(id, (word32)len, idHash) != 0)
252
0
            return WOLFSSL_FAILURE;
253
0
#endif
254
0
        id = idHash;
255
0
        len = SERVER_ID_LEN;
256
0
    }
257
258
0
    if (newSession == 0) {
259
0
        session = wolfSSL_GetSessionClient(ssl, id, len);
260
0
        if (session) {
261
0
            if (wolfSSL_SetSession(ssl, session) != WOLFSSL_SUCCESS) {
262
            #ifdef HAVE_EXT_CACHE
263
                wolfSSL_FreeSession(ssl->ctx, session);
264
            #endif
265
0
                WOLFSSL_MSG("wolfSSL_SetSession failed");
266
0
                session = NULL;
267
0
            }
268
0
        }
269
0
    }
270
271
0
    if (session == NULL) {
272
0
        WOLFSSL_MSG("Valid ServerID not cached already");
273
274
0
        ssl->session->idLen = (word16)len;
275
0
        XMEMCPY(ssl->session->serverID, id, (size_t)len);
276
0
    }
277
#ifdef HAVE_EXT_CACHE
278
    else {
279
        wolfSSL_FreeSession(ssl->ctx, session);
280
    }
281
#endif
282
283
0
    return WOLFSSL_SUCCESS;
284
0
}
285
286
#endif /* !NO_CLIENT_CACHE */
287
288
/* TODO: Add SESSION_CACHE_DYNAMIC_MEM support for PERSIST_SESSION_CACHE.
289
 * Need a count of current sessions to get an accurate memsize (totalCount is
290
 * not decremented when sessions are removed).
291
 * Need to determine ideal layout for mem/filesave.
292
 * Also need mem/filesave checking to ensure not restoring non DYNAMIC_MEM
293
 * cache.
294
 */
295
#if defined(PERSIST_SESSION_CACHE) && !defined(SESSION_CACHE_DYNAMIC_MEM)
296
/* get how big the the session cache save buffer needs to be */
297
int wolfSSL_get_session_cache_memsize(void)
298
{
299
    int sz  = (int)(sizeof(SessionCache) + sizeof(cache_header_t));
300
    #ifndef NO_CLIENT_CACHE
301
    sz += (int)(sizeof(ClientCache));
302
    #endif
303
    return sz;
304
}
305
306
/* Persist session cache to memory */
307
int wolfSSL_memsave_session_cache(void* mem, int sz)
308
{
309
    int i;
310
    cache_header_t cache_header;
311
    SessionRow*    row;
312
313
    WOLFSSL_ENTER("wolfSSL_memsave_session_cache");
314
315
    if (mem == NULL) {
316
        return BAD_FUNC_ARG;
317
    }
318
319
    if (sz < wolfSSL_get_session_cache_memsize()) {
320
        WOLFSSL_MSG("Memory buffer too small");
321
        return BUFFER_E;
322
    }
323
324
    XMEMSET(mem, 0, sz);
325
    row = (SessionRow*)((byte*)mem + sizeof(cache_header));
326
327
    cache_header.version   = WOLFSSL_CACHE_VERSION;
328
    cache_header.rows      = SESSION_ROWS;
329
    cache_header.columns   = SESSIONS_PER_ROW;
330
    cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION);
331
    cache_header.clientRows    = CACHE_HEADER_CLIENT_ROWS;
332
    cache_header.clientColumns = CACHE_HEADER_CLIENT_COLUMNS;
333
    XMEMCPY(mem, &cache_header, sizeof(cache_header));
334
335
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
336
    if (SESSION_ROW_RD_LOCK(row) != 0) {
337
        WOLFSSL_MSG("Session cache mutex lock failed");
338
        return BAD_MUTEX_E;
339
    }
340
    #endif
341
    for (i = 0; i < cache_header.rows; ++i) {
342
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
343
        if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) {
344
            WOLFSSL_MSG("Session row cache mutex lock failed");
345
            return BAD_MUTEX_E;
346
        }
347
    #endif
348
349
        XMEMCPY(row++, &SessionCache[i], SIZEOF_SESSION_ROW);
350
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
351
        SESSION_ROW_UNLOCK(&SessionCache[i]);
352
    #endif
353
    }
354
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
355
    SESSION_ROW_UNLOCK(row);
356
    #endif
357
358
    #ifndef NO_CLIENT_CACHE
359
    if (wc_LockMutex(&clisession_mutex) != 0) {
360
        WOLFSSL_MSG("Client cache mutex lock failed");
361
        return BAD_MUTEX_E;
362
    }
363
    XMEMCPY(row, ClientCache, sizeof(ClientCache));
364
    wc_UnLockMutex(&clisession_mutex);
365
    #endif
366
367
    WOLFSSL_LEAVE("wolfSSL_memsave_session_cache", WOLFSSL_SUCCESS);
368
369
    return WOLFSSL_SUCCESS;
370
}
371
372
/* attempt to sanitize a restored session row:
373
 *   - shallow copy pointers are nulled, and ex_data is zeroed.
374
 *   - ticket len is clamped
375
 *   - fields that cannot be meaningfully sanitized will error out if invalid.
376
 *
377
 * returns 0  on success
378
 * returns -1 on error
379
 * */
380
static int SessionSanityPointerSet(int row)
381
{
382
    SessionRow * srow = NULL;
383
    int          ret = 0;
384
    int          j;
385
386
    if (row < 0 || row >= SESSION_ROWS) {
387
        WOLFSSL_MSG_EX("session sanity: bad row index: %d", row);
388
        return -1;
389
    }
390
391
    srow = &SessionCache[row];
392
393
    if (srow->nextIdx < 0 || srow->nextIdx >= SESSIONS_PER_ROW) {
394
        WOLFSSL_MSG_EX("session sanity: bad row cache index: %d",
395
                       srow->nextIdx);
396
        srow->nextIdx = 0;
397
        ret = -1;
398
    }
399
400
    if (srow->totalCount < 0 || srow->totalCount > SESSIONS_PER_ROW) {
401
        WOLFSSL_MSG_EX("session sanity: bad row total count: %d",
402
                       srow->totalCount);
403
        srow->totalCount = 0;
404
        ret = -1;
405
    }
406
407
    /* Reset pointers to safe values after raw copy.
408
     * Don't break early on error, we always sanitize the entire row. */
409
    for (j = 0; j < SESSIONS_PER_ROW; j++) {
410
        WOLFSSL_SESSION * s = &srow->Sessions[j];
411
412
        /* set type and cacheRow index */
413
        s->type = WOLFSSL_SESSION_TYPE_CACHE;
414
        s->cacheRow = row;
415
416
        /* clamp ticketLen */
417
        #ifdef HAVE_SESSION_TICKET
418
        s->ticket = s->staticTicket;
419
        s->ticketLenAlloc = 0;
420
        if (s->ticketLen > SESSION_TICKET_LEN) {
421
            s->ticketLen = SESSION_TICKET_LEN;
422
        }
423
        #endif /* HAVE_SESSION_TICKET */
424
        #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || \
425
            !defined(NO_PSK))
426
        if (s->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ) {
427
            s->ticketNonce.len = MAX_TICKET_NONCE_STATIC_SZ;
428
        }
429
        #if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
430
            (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && \
431
             FIPS_VERSION_GE(5,3)))
432
        s->ticketNonce.data = s->ticketNonce.dataStatic;
433
        #endif /* WOLFSSL_TICKET_NONCE_MALLOC && ... */
434
        #endif /* WOLFSSL_TLS13 && && etc. */
435
436
        #ifdef SESSION_CERTS
437
        if (s->chain.count < 0 || s->chain.count > MAX_CHAIN_DEPTH) {
438
            WOLFSSL_MSG_EX("session sanity: bad chain count: %d",
439
                           s->chain.count);
440
            s->chain.count = 0;
441
            ret = -1;
442
        }
443
444
        if (s->chain.count) {
445
            int k;
446
            for (k = 0; k < s->chain.count; ++k) {
447
                if (s->chain.certs[k].length < 0 ||
448
                    s->chain.certs[k].length > MAX_X509_SIZE) {
449
                    WOLFSSL_MSG_EX("session sanity: cert[%d] bad length: %d",
450
                                   k, s->chain.certs[k].length);
451
                    s->chain.certs[k].length = 0;
452
                    ret = -1;
453
                }
454
            }
455
        }
456
457
        #ifdef WOLFSSL_ALT_CERT_CHAINS
458
        if (s->altChain.count < 0 || s->altChain.count > MAX_CHAIN_DEPTH) {
459
            WOLFSSL_MSG_EX("session sanity: bad altChain count: %d",
460
                           s->altChain.count);
461
            s->altChain.count = 0;
462
            ret = -1;
463
        }
464
465
        if (s->altChain.count) {
466
            int k;
467
            for (k = 0; k < s->altChain.count; ++k) {
468
                if (s->altChain.certs[k].length < 0 ||
469
                    s->altChain.certs[k].length > MAX_X509_SIZE) {
470
                    WOLFSSL_MSG_EX("session sanity: altCert[%d] bad length: %d",
471
                                   k, s->altChain.certs[k].length);
472
                    s->altChain.certs[k].length = 0;
473
                    ret = -1;
474
                }
475
            }
476
        }
477
        #endif /* WOLFSSL_ALT_CERT_CHAINS */
478
        #endif /* SESSION_CERTS */
479
480
        if (s->sessionIDSz > ID_LEN) {
481
            WOLFSSL_MSG_EX("session sanity: sessionIDSz: %d",
482
                           s->sessionIDSz);
483
            s->sessionIDSz = 0;
484
            ret = -1;
485
        }
486
487
        #ifndef NO_CLIENT_CACHE
488
        if (s->idLen > SERVER_ID_LEN) {
489
            WOLFSSL_MSG_EX("session sanity: idLen: %d",
490
                           s->idLen);
491
            s->idLen = 0;
492
            ret = -1;
493
        }
494
        #endif /* NO_CLIENT_CACHE */
495
496
        #ifdef WOLFSSL_SESSION_ID_CTX
497
        /* sessionCtx is deep copied, but can't exceed ID_LEN. */
498
        if (s->sessionCtxSz > ID_LEN) {
499
            WOLFSSL_MSG_EX("session sanity: sessionCtxSz: %d",
500
                           s->sessionCtxSz);
501
            s->sessionCtxSz = 0;
502
            ret = -1;
503
        }
504
        #endif /* WOLFSSL_SESSION_ID_CTX */
505
506
        /* Sanitize the restored session: none of the following fields are
507
         * meaningful after session restoration.
508
         *
509
         * We could null these instead in wolfSSL_[mem]save_session_cache(),
510
         * but that would require an extra scratch copy (because we save from
511
         * the live session). */
512
        #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
513
        s->peer = NULL;
514
        #endif /* SESSION_CERTS && OPENSSL_EXTRA */
515
        #if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
516
        s->rem_sess_cb = NULL;
517
        #endif /* HAVE_EXT_CACHE || HAVE_EX_DATA */
518
        s->heap = NULL;
519
        #ifdef HAVE_EX_DATA
520
        XMEMSET(&s->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA));
521
        s->ownExData = 1;
522
        #endif /* HAVE_EX_DATA */
523
    }
524
525
    return ret;
526
}
527
528
/* Restore the persistent session cache from memory */
529
int wolfSSL_memrestore_session_cache(const void* mem, int sz)
530
{
531
    int    i;
532
    word32 cacheGen;
533
    int    ret = 0;
534
    cache_header_t cache_header;
535
    SessionRow*    row;
536
537
    WOLFSSL_ENTER("wolfSSL_memrestore_session_cache");
538
539
    if (mem == NULL) {
540
        return BAD_FUNC_ARG;
541
    }
542
543
    row = (SessionRow*)((byte*)mem + sizeof(cache_header));
544
545
    if (sz < wolfSSL_get_session_cache_memsize()) {
546
        WOLFSSL_MSG("Memory buffer too small");
547
        return BUFFER_E;
548
    }
549
550
    XMEMCPY(&cache_header, mem, sizeof(cache_header));
551
    if (cache_header.version   != WOLFSSL_CACHE_VERSION ||
552
        cache_header.rows      != SESSION_ROWS ||
553
        cache_header.columns   != SESSIONS_PER_ROW ||
554
        cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION) ||
555
        cache_header.clientRows    != CACHE_HEADER_CLIENT_ROWS ||
556
        cache_header.clientColumns != CACHE_HEADER_CLIENT_COLUMNS) {
557
558
        WOLFSSL_MSG("Session cache header match failed");
559
        return CACHE_MATCH_ERROR;
560
    }
561
562
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
563
    if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) {
564
        WOLFSSL_MSG("Session cache mutex lock failed");
565
        return BAD_MUTEX_E;
566
    }
567
    #endif
568
    for (i = 0; i < cache_header.rows; ++i) {
569
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
570
        if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) {
571
            WOLFSSL_MSG("Session row cache mutex lock failed");
572
            return BAD_MUTEX_E;
573
        }
574
    #endif
575
576
        cacheGen = SessionCache[i].cacheGen;
577
        XMEMCPY(&SessionCache[i], row++, SIZEOF_SESSION_ROW);
578
        /* Generations already handed to live handles must not be reissued.
579
         * The entry keeps the one it was saved with, which is the generation
580
         * the restored ClientCache entries were issued against. */
581
        if (SessionCache[i].cacheGen < cacheGen)
582
            SessionCache[i].cacheGen = cacheGen;
583
584
        ret = SessionSanityPointerSet(i);
585
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
586
        SESSION_ROW_UNLOCK(&SessionCache[i]);
587
    #endif
588
        if (ret) {
589
            /*  session data is corrupted
590
             *  Wiping the rows must not restart the generation counters. */
591
            int j;
592
            for (j = 0; j < SESSION_ROWS; j++) {
593
                cacheGen = SessionCache[j].cacheGen;
594
                XMEMSET(&SessionCache[j], 0, sizeof(SessionCache[j]));
595
                SessionCache[j].cacheGen = cacheGen;
596
            }
597
            break;
598
        }
599
    }
600
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
601
    SESSION_ROW_UNLOCK(&SessionCache[0]);
602
    #endif
603
604
    if (ret == 0) {
605
        #ifndef NO_CLIENT_CACHE
606
        if (wc_LockMutex(&clisession_mutex) != 0) {
607
            WOLFSSL_MSG("Client cache mutex lock failed");
608
            return BAD_MUTEX_E;
609
        }
610
        XMEMCPY(ClientCache, row, sizeof(ClientCache));
611
        wc_UnLockMutex(&clisession_mutex);
612
        #endif
613
    }
614
615
    WOLFSSL_LEAVE("wolfSSL_memrestore_session_cache",
616
                  ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
617
618
    return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
619
}
620
621
#if !defined(NO_FILESYSTEM)
622
623
/* Persist session cache to file */
624
/* doesn't use memsave because of additional memory use */
625
int wolfSSL_save_session_cache(const char *fname)
626
{
627
    XFILE  file;
628
    int    ret;
629
    int    rc = WOLFSSL_SUCCESS;
630
    int    i;
631
    cache_header_t cache_header;
632
633
    WOLFSSL_ENTER("wolfSSL_save_session_cache");
634
635
    file = wc_fopen_owner_only(fname);
636
    if (file == XBADFILE) {
637
        WOLFSSL_MSG("Couldn't open session cache save file");
638
        return WOLFSSL_BAD_FILE;
639
    }
640
    cache_header.version   = WOLFSSL_CACHE_VERSION;
641
    cache_header.rows      = SESSION_ROWS;
642
    cache_header.columns   = SESSIONS_PER_ROW;
643
    cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION);
644
    cache_header.clientRows    = CACHE_HEADER_CLIENT_ROWS;
645
    cache_header.clientColumns = CACHE_HEADER_CLIENT_COLUMNS;
646
647
    /* cache header */
648
    ret = (int)XFWRITE(&cache_header, sizeof cache_header, 1, file);
649
    if (ret != 1) {
650
        WOLFSSL_MSG("Session cache header file write failed");
651
        XFCLOSE(file);
652
        return FWRITE_ERROR;
653
    }
654
655
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
656
    if (SESSION_ROW_RD_LOCK(&SessionCache[0]) != 0) {
657
        WOLFSSL_MSG("Session cache mutex lock failed");
658
        XFCLOSE(file);
659
        return BAD_MUTEX_E;
660
    }
661
    #endif
662
    /* session cache */
663
    for (i = 0; i < cache_header.rows; ++i) {
664
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
665
        if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) {
666
            WOLFSSL_MSG("Session row cache mutex lock failed");
667
            XFCLOSE(file);
668
            return BAD_MUTEX_E;
669
        }
670
    #endif
671
672
        ret = (int)XFWRITE(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file);
673
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
674
        SESSION_ROW_UNLOCK(&SessionCache[i]);
675
    #endif
676
        if (ret != 1) {
677
            WOLFSSL_MSG("Session cache member file write failed");
678
            rc = FWRITE_ERROR;
679
            break;
680
        }
681
    }
682
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
683
    SESSION_ROW_UNLOCK(&SessionCache[0]);
684
    #endif
685
686
    #ifndef NO_CLIENT_CACHE
687
    /* client cache */
688
    if (wc_LockMutex(&clisession_mutex) != 0) {
689
        WOLFSSL_MSG("Client cache mutex lock failed");
690
        XFCLOSE(file);
691
        return BAD_MUTEX_E;
692
    }
693
    ret = (int)XFWRITE(ClientCache, sizeof(ClientCache), 1, file);
694
    if (ret != 1) {
695
        WOLFSSL_MSG("Client cache member file write failed");
696
        rc = FWRITE_ERROR;
697
    }
698
    wc_UnLockMutex(&clisession_mutex);
699
    #endif /* !NO_CLIENT_CACHE */
700
701
    XFCLOSE(file);
702
    WOLFSSL_LEAVE("wolfSSL_save_session_cache", rc);
703
704
    return rc;
705
}
706
707
/* Restore the persistent session cache from file */
708
/* doesn't use memstore because of additional memory use */
709
int wolfSSL_restore_session_cache(const char *fname)
710
{
711
    XFILE  file;
712
    int    rc = WOLFSSL_SUCCESS;
713
    int    ret;
714
    int    i;
715
    word32 cacheGen;
716
    cache_header_t cache_header;
717
718
    WOLFSSL_ENTER("wolfSSL_restore_session_cache");
719
720
    file = XFOPEN(fname, "rb");
721
    if (file == XBADFILE) {
722
        WOLFSSL_MSG_EX("Couldn't open session cache save file: %s", fname);
723
        return WOLFSSL_BAD_FILE;
724
    }
725
    /* cache header */
726
    ret = (int)XFREAD(&cache_header, sizeof(cache_header), 1, file);
727
    if (ret != 1) {
728
        WOLFSSL_MSG_EX("Session cache header file read failed: %s: %d", fname,
729
                       ret);
730
        XFCLOSE(file);
731
        return FREAD_ERROR;
732
    }
733
    if (cache_header.version   != WOLFSSL_CACHE_VERSION ||
734
        cache_header.rows      != SESSION_ROWS ||
735
        cache_header.columns   != SESSIONS_PER_ROW ||
736
        cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION) ||
737
        cache_header.clientRows    != CACHE_HEADER_CLIENT_ROWS ||
738
        cache_header.clientColumns != CACHE_HEADER_CLIENT_COLUMNS) {
739
740
        WOLFSSL_MSG_EX("Session cache header match failed: %s", fname);
741
        XFCLOSE(file);
742
        return CACHE_MATCH_ERROR;
743
    }
744
745
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
746
    if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) {
747
        WOLFSSL_MSG("Session cache mutex lock failed");
748
        XFCLOSE(file);
749
        return BAD_MUTEX_E;
750
    }
751
    #endif
752
    /* session cache */
753
    for (i = 0; i < cache_header.rows; ++i) {
754
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
755
        if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) {
756
            WOLFSSL_MSG("Session row cache mutex lock failed");
757
            XFCLOSE(file);
758
            return BAD_MUTEX_E;
759
        }
760
    #endif
761
762
        cacheGen = SessionCache[i].cacheGen;
763
        ret = (int)XFREAD(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file);
764
        if (ret != 1) {
765
            WOLFSSL_MSG("Session cache member file read failed");
766
            rc = FREAD_ERROR;
767
        }
768
        /* Generations already handed to live handles must not be reissued.
769
         * The entry keeps the one it was saved with, which is the generation
770
         * the restored ClientCache entries were issued against. */
771
        if (rc != WOLFSSL_SUCCESS || SessionCache[i].cacheGen < cacheGen) {
772
            SessionCache[i].cacheGen = cacheGen;
773
        }
774
775
        if (rc == WOLFSSL_SUCCESS) {
776
            /* file read success. now sanitize the imported session row. */
777
            ret = SessionSanityPointerSet(i);
778
779
            if (ret) {
780
                /* session data is corrupted */
781
                rc = WOLFSSL_FAILURE;
782
            }
783
        }
784
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
785
        SESSION_ROW_UNLOCK(&SessionCache[i]);
786
    #endif
787
        if (rc != WOLFSSL_SUCCESS) {
788
            int j;
789
            /* Wiping the rows must not restart the generation counters. */
790
            for (j = 0; j < SESSION_ROWS; j++) {
791
                cacheGen = SessionCache[j].cacheGen;
792
                XMEMSET(&SessionCache[j], 0, sizeof(SessionCache[j]));
793
                SessionCache[j].cacheGen = cacheGen;
794
            }
795
            break;
796
        }
797
    }
798
    #ifndef ENABLE_SESSION_CACHE_ROW_LOCK
799
    SESSION_ROW_UNLOCK(&SessionCache[0]);
800
    #endif
801
802
    if (rc == WOLFSSL_SUCCESS) {
803
        #ifndef NO_CLIENT_CACHE
804
        /* client cache */
805
        if (wc_LockMutex(&clisession_mutex) != 0) {
806
            WOLFSSL_MSG("Client cache mutex lock failed");
807
            XFCLOSE(file);
808
            return BAD_MUTEX_E;
809
        }
810
        ret = (int)XFREAD(ClientCache, sizeof(ClientCache), 1, file);
811
        if (ret != 1) {
812
            WOLFSSL_MSG("Client cache member file read failed");
813
            XMEMSET(ClientCache, 0, sizeof ClientCache);
814
            rc = FREAD_ERROR;
815
        }
816
        wc_UnLockMutex(&clisession_mutex);
817
        #endif /* !NO_CLIENT_CACHE */
818
    }
819
820
    XFCLOSE(file);
821
    WOLFSSL_LEAVE("wolfSSL_restore_session_cache", rc);
822
823
    return rc;
824
}
825
826
#endif /* !NO_FILESYSTEM */
827
#endif /* PERSIST_SESSION_CACHE && !SESSION_CACHE_DYNAMIC_MEM */
828
829
/* on by default if built in but allow user to turn off */
830
WOLFSSL_ABI
831
long wolfSSL_CTX_set_session_cache_mode(WOLFSSL_CTX* ctx, long mode)
832
0
{
833
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_session_cache_mode");
834
835
0
    if (ctx == NULL)
836
0
        return WOLFSSL_FAILURE;
837
838
0
    if (mode == WOLFSSL_SESS_CACHE_OFF) {
839
0
        ctx->sessionCacheOff = 1;
840
#ifdef HAVE_EXT_CACHE
841
        ctx->internalCacheOff = 1;
842
        ctx->internalCacheLookupOff = 1;
843
#endif
844
0
    }
845
846
0
    if ((mode & WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR) != 0)
847
0
        ctx->sessionCacheFlushOff = 1;
848
849
#ifdef HAVE_EXT_CACHE
850
    /* WOLFSSL_SESS_CACHE_NO_INTERNAL activates both if's */
851
    if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE) != 0)
852
        ctx->internalCacheOff = 1;
853
    if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP) != 0)
854
        ctx->internalCacheLookupOff = 1;
855
#endif
856
857
0
    return WOLFSSL_SUCCESS;
858
0
}
859
860
#ifdef OPENSSL_EXTRA
861
#ifdef HAVE_MAX_FRAGMENT
862
/* return the max fragment size set when handshake was negotiated */
863
unsigned char wolfSSL_SESSION_get_max_fragment_length(WOLFSSL_SESSION* session)
864
{
865
    session = ClientSessionToSession(session);
866
    if (session == NULL) {
867
        return 0;
868
    }
869
870
    return session->mfl;
871
}
872
#endif
873
874
875
/* Get the session cache mode for CTX
876
 *
877
 * ctx  WOLFSSL_CTX struct to get cache mode from
878
 *
879
 * Returns a bit mask that has the session cache mode */
880
long wolfSSL_CTX_get_session_cache_mode(WOLFSSL_CTX* ctx)
881
{
882
    long m = 0;
883
884
    WOLFSSL_ENTER("wolfSSL_CTX_get_session_cache_mode");
885
886
    if (ctx == NULL) {
887
        return m;
888
    }
889
890
    if (ctx->sessionCacheOff != 1) {
891
        m |= WOLFSSL_SESS_CACHE_SERVER;
892
    }
893
894
    if (ctx->sessionCacheFlushOff == 1) {
895
        m |= WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR;
896
    }
897
898
#ifdef HAVE_EXT_CACHE
899
    if (ctx->internalCacheOff == 1) {
900
        m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE;
901
    }
902
    if (ctx->internalCacheLookupOff == 1) {
903
        m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
904
    }
905
#endif
906
907
    return m;
908
}
909
#endif /* OPENSSL_EXTRA */
910
911
#endif /* !NO_SESSION_CACHE */
912
913
#ifndef NO_SESSION_CACHE
914
915
WOLFSSL_ABI
916
void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm)
917
0
{
918
    /* static table now, no flushing needed */
919
0
    (void)ctx;
920
0
    (void)tm;
921
0
}
922
923
void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm)
924
0
{
925
0
    int i, j;
926
927
0
    (void)ctx;
928
0
    WOLFSSL_ENTER("wolfSSL_flush_sessions");
929
0
    for (i = 0; i < SESSION_ROWS; ++i) {
930
0
        if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) {
931
0
            WOLFSSL_MSG("Session cache mutex lock failed");
932
0
            return;
933
0
        }
934
0
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
935
#ifdef SESSION_CACHE_DYNAMIC_MEM
936
            WOLFSSL_SESSION* s = SessionCache[i].Sessions[j];
937
#else
938
0
            WOLFSSL_SESSION* s = &SessionCache[i].Sessions[j];
939
0
#endif
940
0
            if (
941
#ifdef SESSION_CACHE_DYNAMIC_MEM
942
                s != NULL &&
943
#endif
944
0
                s->sessionIDSz > 0 &&
945
0
                s->bornOn + s->timeout < (word32)tm
946
0
                )
947
0
            {
948
0
                EvictSessionFromCache(s);
949
#ifdef SESSION_CACHE_DYNAMIC_MEM
950
                XFREE(s, s->heap, DYNAMIC_TYPE_SESSION);
951
                SessionCache[i].Sessions[j] = NULL;
952
#endif
953
0
            }
954
0
        }
955
0
        SESSION_ROW_UNLOCK(&SessionCache[i]);
956
0
    }
957
0
}
958
959
960
/* set ssl session timeout in seconds */
961
WOLFSSL_ABI
962
int wolfSSL_set_timeout(WOLFSSL* ssl, unsigned int to)
963
0
{
964
0
    if (ssl == NULL)
965
0
        return BAD_FUNC_ARG;
966
967
0
    if (to == 0)
968
0
        to = WOLFSSL_SESSION_TIMEOUT;
969
0
    ssl->timeout = to;
970
971
0
    return WOLFSSL_SUCCESS;
972
0
}
973
974
#ifndef NO_TLS
975
/**
976
 * Sets ctx session timeout in seconds.
977
 * The timeout value set here should be reflected in the
978
 * "session ticket lifetime hint" if this API works in the openssl compat-layer.
979
 * Therefore wolfSSL_CTX_set_TicketHint is called internally.
980
 * Arguments:
981
 *  - ctx  WOLFSSL_CTX object which the timeout is set to
982
 *  - to   timeout value in second
983
 * Returns:
984
 *  WOLFSSL_SUCCESS on success, BAD_FUNC_ARG on failure.
985
 *  When WOLFSSL_ERROR_CODE_OPENSSL is defined, returns previous timeout value
986
 *  on success, BAD_FUNC_ARG on failure.
987
 */
988
WOLFSSL_ABI
989
int wolfSSL_CTX_set_timeout(WOLFSSL_CTX* ctx, unsigned int to)
990
0
{
991
    #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
992
    word32 prev_timeout = 0;
993
    #endif
994
995
0
    int ret = WOLFSSL_SUCCESS;
996
0
    (void)ret;
997
998
0
    if (ctx == NULL)
999
0
        ret = BAD_FUNC_ARG;
1000
1001
0
    if (ret == WOLFSSL_SUCCESS) {
1002
    #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
1003
        prev_timeout = ctx->timeout;
1004
    #endif
1005
0
        if (to == 0) {
1006
0
            ctx->timeout = WOLFSSL_SESSION_TIMEOUT;
1007
0
        }
1008
0
        else {
1009
0
            ctx->timeout = to;
1010
0
        }
1011
0
    }
1012
#if defined(OPENSSL_EXTRA) && defined(HAVE_SESSION_TICKET) && \
1013
   !defined(NO_WOLFSSL_SERVER)
1014
    if (ret == WOLFSSL_SUCCESS) {
1015
        if (to == 0) {
1016
            ret = wolfSSL_CTX_set_TicketHint(ctx, SESSION_TICKET_HINT_DEFAULT);
1017
        }
1018
        else {
1019
            ret = wolfSSL_CTX_set_TicketHint(ctx, (int)to);
1020
        }
1021
    }
1022
#endif /* OPENSSL_EXTRA && HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER */
1023
1024
#if defined(WOLFSSL_ERROR_CODE_OPENSSL)
1025
    if (ret == WOLFSSL_SUCCESS) {
1026
        return (int)prev_timeout;
1027
    }
1028
    else {
1029
        return ret;
1030
    }
1031
#else
1032
0
    return ret;
1033
0
#endif /* WOLFSSL_ERROR_CODE_OPENSSL */
1034
0
}
1035
#endif /* !NO_TLS */
1036
1037
#ifndef NO_CLIENT_CACHE
1038
1039
/* Get Session from Client cache based on id/len, return NULL on failure */
1040
WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len)
1041
0
{
1042
0
    WOLFSSL_SESSION* ret = NULL;
1043
0
    word32          row;
1044
0
    int             idx;
1045
0
    int             count;
1046
0
    int             error = 0;
1047
0
    ClientSession*  clSess;
1048
1049
0
    WOLFSSL_ENTER("wolfSSL_GetSessionClient");
1050
1051
0
    if (ssl->ctx->sessionCacheOff) {
1052
0
        WOLFSSL_MSG("Session Cache off");
1053
0
        return NULL;
1054
0
    }
1055
1056
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
1057
0
        return NULL;
1058
1059
0
    len = (int)min(SERVER_ID_LEN, (word32)len);
1060
1061
    /* Do not access ssl->ctx->get_sess_cb from here. It is using a different
1062
     * set of ID's */
1063
1064
0
    row = HashObject(id, (word32)len, &error) % CLIENT_SESSION_ROWS;
1065
0
    if (error != 0) {
1066
0
        WOLFSSL_MSG("Hash session failed");
1067
0
        return NULL;
1068
0
    }
1069
1070
0
    if (wc_LockMutex(&clisession_mutex) != 0) {
1071
0
        WOLFSSL_MSG("Client cache mutex lock failed");
1072
0
        return NULL;
1073
0
    }
1074
1075
    /* start from most recently used */
1076
0
    count = (int)min((word32)ClientCache[row].totalCount,
1077
0
        CLIENT_SESSIONS_PER_ROW);
1078
0
    idx = ClientCache[row].nextIdx - 1;
1079
0
    if (idx < 0 || idx >= CLIENT_SESSIONS_PER_ROW) {
1080
        /* if back to front, the previous was end */
1081
0
        idx = CLIENT_SESSIONS_PER_ROW - 1;
1082
0
    }
1083
0
    clSess = ClientCache[row].Clients;
1084
1085
0
    for (; count > 0; --count) {
1086
0
        WOLFSSL_SESSION* current;
1087
0
        SessionRow* sessRow;
1088
1089
0
        if (clSess[idx].serverRow >= SESSION_ROWS ||
1090
0
            clSess[idx].serverIdx >= SESSIONS_PER_ROW ) {
1091
0
            WOLFSSL_MSG("Client cache serverRow or serverIdx invalid");
1092
0
            break;
1093
0
        }
1094
1095
        /* lock row */
1096
0
        sessRow = &SessionCache[clSess[idx].serverRow];
1097
0
        if (SESSION_ROW_RD_LOCK(sessRow) != 0) {
1098
0
            WOLFSSL_MSG("Session cache row lock failure");
1099
0
            break;
1100
0
        }
1101
1102
    #ifdef SESSION_CACHE_DYNAMIC_MEM
1103
        current = sessRow->Sessions[clSess[idx].serverIdx];
1104
    #else
1105
0
        current = &sessRow->Sessions[clSess[idx].serverIdx];
1106
0
    #endif
1107
        /* Require the same length as well as the same bytes. Comparing only
1108
         * the requested length lets a short ID alias the prefix of a longer
1109
         * cached one, mixing sessions the application meant to keep apart. */
1110
0
        if (current && current->idLen == (word16)len &&
1111
0
                XMEMCMP(current->serverID, id, (unsigned long)len) == 0) {
1112
0
            WOLFSSL_MSG("Found a serverid match for client");
1113
0
            if (LowResTimer() < (current->bornOn + current->timeout)) {
1114
0
                WOLFSSL_MSG("Session valid");
1115
0
                ret = current;
1116
0
                SESSION_ROW_UNLOCK(sessRow);
1117
0
                break;
1118
0
            } else {
1119
0
                WOLFSSL_MSG("Session timed out");  /* could have more for id */
1120
0
            }
1121
0
        } else {
1122
0
            WOLFSSL_MSG("ServerID not a match from client table");
1123
0
        }
1124
0
        SESSION_ROW_UNLOCK(sessRow);
1125
1126
0
        idx = idx > 0 ? idx - 1 : CLIENT_SESSIONS_PER_ROW - 1;
1127
0
    }
1128
1129
0
    wc_UnLockMutex(&clisession_mutex);
1130
1131
0
    return ret;
1132
0
}
1133
1134
#endif /* !NO_CLIENT_CACHE */
1135
1136
static int SslSessionCacheOff(const WOLFSSL* ssl,
1137
    const WOLFSSL_SESSION* session)
1138
{
1139
    (void)session;
1140
    return ssl->options.sessionCacheOff
1141
    #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_FORCE_CACHE_ON_TICKET)
1142
                && session->ticketLen == 0
1143
    #endif
1144
                ;
1145
}
1146
1147
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) &&                  \
1148
    defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
1149
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1150
/**
1151
 * SessionTicketNoncePrealloc() - prealloc a buffer for ticket nonces
1152
 * @output: [in] pointer to WOLFSSL_SESSION object that will soon be a
1153
 * destination of a session duplication
1154
 * @buf: [out] address of the preallocated buf
1155
 * @len: [out] len of the preallocated buf
1156
 *
1157
 * prealloc a buffer that will likely suffice to contain a ticket nonce. It's
1158
 * used when copying session under lock, when syscalls need to be avoided. If
1159
 * output already has a dynamic buffer, it's reused.
1160
 */
1161
static int SessionTicketNoncePrealloc(byte** buf, byte* len, void *heap)
1162
{
1163
    (void)heap;
1164
1165
    *buf = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_NONCE_LEN, heap,
1166
        DYNAMIC_TYPE_SESSION_TICK);
1167
    if (*buf == NULL) {
1168
        WOLFSSL_MSG("Failed to preallocate ticket nonce buffer");
1169
        *len = 0;
1170
        return 1;
1171
    }
1172
1173
    *len = PREALLOC_SESSION_TICKET_NONCE_LEN;
1174
    return 0;
1175
}
1176
#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */
1177
1178
static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input,
1179
    WOLFSSL_SESSION* output, int avoidSysCalls, int transferExData,
1180
    byte* ticketNonceBuf, byte* ticketNonceLen, byte* preallocUsed);
1181
1182
/* Client entries sit one row over so both sides of a connection never share
1183
 * a row. */
1184
static word32 SessionCacheRow(const byte* id, int side, int* error)
1185
260
{
1186
260
    word32 row = HashObject(id, ID_LEN, error) % SESSION_ROWS;
1187
1188
260
    if (side == WOLFSSL_CLIENT_END)
1189
0
        row = (row + 1) % SESSION_ROWS;
1190
260
    return row;
1191
260
}
1192
1193
void TlsSessionCacheUnlockRow(word32 row)
1194
0
{
1195
0
    SessionRow* sessRow;
1196
1197
0
    sessRow = &SessionCache[row];
1198
0
    (void)sessRow;
1199
0
    SESSION_ROW_UNLOCK(sessRow);
1200
0
}
1201
1202
/* Don't use this function directly. Use TlsSessionCacheGetAndRdLock and
1203
 * TlsSessionCacheGetAndWrLock to fully utilize compiler const support. */
1204
static int TlsSessionCacheGetAndLock(const byte *id,
1205
    const WOLFSSL_SESSION **sess, word32 *lockedRow, byte readOnly, byte side)
1206
260
{
1207
260
    SessionRow *sessRow;
1208
260
    const WOLFSSL_SESSION *s;
1209
260
    word32 row;
1210
260
    int count;
1211
260
    int error;
1212
260
    int idx;
1213
1214
260
    *sess = NULL;
1215
260
    row = SessionCacheRow(id, side, &error);
1216
260
    if (error != 0)
1217
2
        return error;
1218
258
    sessRow = &SessionCache[row];
1219
258
    if (readOnly)
1220
183
        error = SESSION_ROW_RD_LOCK(sessRow);
1221
75
    else
1222
75
        error = SESSION_ROW_WR_LOCK(sessRow);
1223
258
    if (error != 0)
1224
0
        return FATAL_ERROR;
1225
1226
    /* start from most recently used */
1227
258
    count = (int)min((word32)sessRow->totalCount, SESSIONS_PER_ROW);
1228
258
    idx = sessRow->nextIdx - 1;
1229
258
    if (idx < 0 || idx >= SESSIONS_PER_ROW) {
1230
258
        idx = SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */
1231
258
    }
1232
258
    for (; count > 0; --count) {
1233
#ifdef SESSION_CACHE_DYNAMIC_MEM
1234
        s = sessRow->Sessions[idx];
1235
#else
1236
0
        s = &sessRow->Sessions[idx];
1237
0
#endif
1238
        /* match session ID value and length */
1239
0
        if (s && s->sessionIDSz == ID_LEN && s->side == side &&
1240
0
                XMEMCMP(s->sessionID, id, ID_LEN) == 0) {
1241
0
            *sess = s;
1242
0
            break;
1243
0
        }
1244
0
        idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1;
1245
0
    }
1246
258
    if (*sess == NULL) {
1247
258
        SESSION_ROW_UNLOCK(sessRow);
1248
258
    }
1249
0
    else {
1250
0
        *lockedRow = row;
1251
0
    }
1252
1253
258
    return 0;
1254
258
}
1255
1256
static int CheckSessionMatch(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess)
1257
0
{
1258
0
    if (ssl == NULL || sess == NULL)
1259
0
        return 0;
1260
#ifdef OPENSSL_EXTRA
1261
    if (ssl->sessionCtxSz > 0 && (ssl->sessionCtxSz != sess->sessionCtxSz ||
1262
           XMEMCMP(ssl->sessionCtx, sess->sessionCtx, sess->sessionCtxSz) != 0))
1263
        return 0;
1264
#endif
1265
0
    if (IsAtLeastTLSv1_3(ssl->version) != IsAtLeastTLSv1_3(sess->version))
1266
0
        return 0;
1267
0
    return 1;
1268
0
}
1269
1270
int TlsSessionCacheGetAndRdLock(const byte *id, const WOLFSSL_SESSION **sess,
1271
        word32 *lockedRow, byte side)
1272
183
{
1273
183
    return TlsSessionCacheGetAndLock(id, sess, lockedRow, 1, side);
1274
183
}
1275
1276
int TlsSessionCacheGetAndWrLock(const byte *id, WOLFSSL_SESSION **sess,
1277
        word32 *lockedRow, byte side)
1278
77
{
1279
77
    return TlsSessionCacheGetAndLock(id, (const WOLFSSL_SESSION**)sess,
1280
77
            lockedRow, 0, side);
1281
77
}
1282
1283
static int GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output,
1284
        byte internalOnly)
1285
0
{
1286
0
    const WOLFSSL_SESSION* sess = NULL;
1287
0
    const byte*  id = NULL;
1288
0
    word32       row;
1289
0
    int          error = 0;
1290
#ifdef HAVE_SESSION_TICKET
1291
    WC_DECLARE_VAR(tmpTicket, byte, PREALLOC_SESSION_TICKET_LEN, 0);
1292
#ifdef WOLFSSL_TLS13
1293
    byte *preallocNonce = NULL;
1294
    byte preallocNonceLen = 0;
1295
    byte preallocNonceUsed = 0;
1296
#endif /* WOLFSSL_TLS13 */
1297
    byte         tmpBufSet = 0;
1298
#endif
1299
0
    byte         bogusID[ID_LEN];
1300
0
    byte         bogusIDSz = 0;
1301
1302
0
    WOLFSSL_ENTER("GetSessionFromCache");
1303
1304
0
    (void)internalOnly;
1305
1306
0
    if (output == NULL) {
1307
0
        WOLFSSL_MSG("NULL output");
1308
0
        return WOLFSSL_FAILURE;
1309
0
    }
1310
1311
0
    if (SslSessionCacheOff(ssl, ssl->session))
1312
0
        return WOLFSSL_FAILURE;
1313
1314
0
    if (ssl->options.haveSessionId == 0 && !ssl->session->haveAltSessionID)
1315
0
        return WOLFSSL_FAILURE;
1316
1317
#ifdef HAVE_SESSION_TICKET
1318
    if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1)
1319
        return WOLFSSL_FAILURE;
1320
#endif
1321
1322
0
    XMEMSET(bogusID, 0, sizeof(bogusID));
1323
0
    if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL
1324
0
            && !ssl->session->haveAltSessionID)
1325
0
        id = ssl->arrays->sessionID;
1326
0
    else if (ssl->session->haveAltSessionID) {
1327
0
        id = ssl->session->altSessionID;
1328
        /* We want to restore the bogus ID for TLS compatibility */
1329
0
        if (output == ssl->session) {
1330
0
            XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN);
1331
0
            bogusIDSz = ssl->session->sessionIDSz;
1332
0
        }
1333
0
    }
1334
0
    else
1335
0
        id = ssl->session->sessionID;
1336
1337
1338
#ifdef HAVE_EXT_CACHE
1339
    if (!internalOnly && ssl->ctx->get_sess_cb != NULL) {
1340
        int copy = 1;
1341
        int found = 0;
1342
        WOLFSSL_SESSION* extSess;
1343
        /* Attempt to retrieve the session from the external cache. */
1344
        WOLFSSL_MSG("Calling external session cache");
1345
        extSess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, &copy);
1346
        if ((extSess != NULL)
1347
                && CheckSessionMatch(ssl, extSess)
1348
            ) {
1349
            WOLFSSL_MSG("Session found in external cache");
1350
            found = 1;
1351
1352
            error = wolfSSL_DupSession(extSess, output, 0);
1353
#ifdef HAVE_EX_DATA
1354
            extSess->ownExData = 1;
1355
            output->ownExData = 0;
1356
#endif
1357
            /* We want to restore the bogus ID for TLS compatibility */
1358
            if (ssl->session->haveAltSessionID &&
1359
                    output == ssl->session) {
1360
                XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN);
1361
                ssl->session->sessionIDSz = bogusIDSz;
1362
            }
1363
        }
1364
        if (extSess != NULL && !copy)
1365
            wolfSSL_FreeSession(ssl->ctx, extSess);
1366
        if (found)
1367
            return error;
1368
        WOLFSSL_MSG("Session not found in external cache");
1369
    }
1370
1371
    if (ssl->options.internalCacheLookupOff) {
1372
        WOLFSSL_MSG("Internal cache lookup turned off");
1373
        return WOLFSSL_FAILURE;
1374
    }
1375
#endif
1376
1377
#ifdef HAVE_SESSION_TICKET
1378
    if (output->ticket == NULL ||
1379
            output->ticketLenAlloc < PREALLOC_SESSION_TICKET_LEN) {
1380
#ifdef WOLFSSL_SMALL_STACK
1381
        tmpTicket = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_LEN, output->heap,
1382
                DYNAMIC_TYPE_TMP_BUFFER);
1383
        if (tmpTicket == NULL) {
1384
            WOLFSSL_MSG("tmpTicket malloc failed");
1385
            return WOLFSSL_FAILURE;
1386
        }
1387
#endif
1388
        if (output->ticketLenAlloc)
1389
            XFREE(output->ticket, output->heap, DYNAMIC_TYPE_SESSION_TICK);
1390
        /* cppcheck-suppress autoVariables */
1391
        output->ticket = tmpTicket;
1392
        output->ticketLenAlloc = PREALLOC_SESSION_TICKET_LEN;
1393
        output->ticketLen = 0;
1394
        tmpBufSet = 1;
1395
    }
1396
#endif
1397
1398
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
1399
    if (output->peer != NULL) {
1400
        wolfSSL_X509_free(output->peer);
1401
        output->peer = NULL;
1402
    }
1403
#endif
1404
1405
#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) &&                  \
1406
    defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
1407
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1408
    if (output->ticketNonce.data != output->ticketNonce.dataStatic) {
1409
        XFREE(output->ticketNonce.data, output->heap,
1410
            DYNAMIC_TYPE_SESSION_TICK);
1411
        output->ticketNonce.data = output->ticketNonce.dataStatic;
1412
        output->ticketNonce.len = 0;
1413
    }
1414
    error = SessionTicketNoncePrealloc(&preallocNonce, &preallocNonceLen,
1415
        output->heap);
1416
    if (error != 0) {
1417
        if (tmpBufSet) {
1418
            output->ticket = output->staticTicket;
1419
            output->ticketLenAlloc = 0;
1420
        }
1421
        WC_FREE_VAR_EX(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER);
1422
        return WOLFSSL_FAILURE;
1423
    }
1424
#endif /* WOLFSSL_TLS13 && HAVE_SESSION_TICKET*/
1425
1426
    /* init to avoid clang static analyzer false positive */
1427
0
    row = 0;
1428
0
    error = TlsSessionCacheGetAndRdLock(id, &sess, &row,
1429
0
        (byte)ssl->options.side);
1430
0
    error = (error == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
1431
0
    if (error != WOLFSSL_SUCCESS || sess == NULL) {
1432
0
        WOLFSSL_MSG("Get Session from cache failed");
1433
0
        error = WOLFSSL_FAILURE;
1434
#ifdef HAVE_SESSION_TICKET
1435
        if (tmpBufSet) {
1436
            output->ticket = output->staticTicket;
1437
            output->ticketLenAlloc = 0;
1438
        }
1439
#ifdef WOLFSSL_TLS13
1440
        XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK);
1441
        preallocNonce = NULL;
1442
#endif /* WOLFSSL_TLS13 */
1443
#ifdef WOLFSSL_SMALL_STACK
1444
        XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER);
1445
        tmpTicket = NULL;
1446
#endif
1447
#endif
1448
0
    }
1449
0
    else {
1450
0
        if (!CheckSessionMatch(ssl, sess)) {
1451
0
            WOLFSSL_MSG("Invalid session: can't be used in this context");
1452
0
            TlsSessionCacheUnlockRow(row);
1453
0
            error = WOLFSSL_FAILURE;
1454
0
        }
1455
0
        else if (LowResTimer() >= (sess->bornOn + sess->timeout)) {
1456
0
            WOLFSSL_SESSION* wrSess = NULL;
1457
0
            WOLFSSL_MSG("Invalid session: timed out");
1458
0
            sess = NULL;
1459
0
            TlsSessionCacheUnlockRow(row);
1460
            /* Attempt to get a write lock */
1461
0
            error = TlsSessionCacheGetAndWrLock(id, &wrSess, &row,
1462
0
                    (byte)ssl->options.side);
1463
0
            if (error == 0 && wrSess != NULL) {
1464
0
                EvictSessionFromCache(wrSess);
1465
0
                TlsSessionCacheUnlockRow(row);
1466
0
            }
1467
0
            error = WOLFSSL_FAILURE;
1468
0
        }
1469
0
    }
1470
1471
    /* mollify confused cppcheck nullPointer warning. */
1472
0
    if (sess == NULL)
1473
0
        error = WOLFSSL_FAILURE;
1474
1475
0
    if (error == WOLFSSL_SUCCESS) {
1476
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13)
1477
        error = wolfSSL_DupSessionEx(sess, output, 1, 1,
1478
            preallocNonce, &preallocNonceLen, &preallocNonceUsed);
1479
#else
1480
0
        error = wolfSSL_DupSession(sess, output, 1);
1481
0
#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */
1482
#ifdef HAVE_EX_DATA
1483
        output->ownExData = !sess->ownExData; /* Session may own ex_data */
1484
#endif
1485
0
        TlsSessionCacheUnlockRow(row);
1486
0
    }
1487
1488
    /* We want to restore the bogus ID for TLS compatibility */
1489
0
    if (ssl->session->haveAltSessionID &&
1490
0
            output == ssl->session) {
1491
0
        XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN);
1492
0
        ssl->session->sessionIDSz = bogusIDSz;
1493
0
    }
1494
1495
#ifdef HAVE_SESSION_TICKET
1496
    if (tmpBufSet) {
1497
        if (error == WOLFSSL_SUCCESS) {
1498
            if (output->ticketLen > SESSION_TICKET_LEN) {
1499
                output->ticket = (byte*)XMALLOC(output->ticketLen, output->heap,
1500
                        DYNAMIC_TYPE_SESSION_TICK);
1501
                if (output->ticket == NULL) {
1502
                    error = WOLFSSL_FAILURE;
1503
                    output->ticket = output->staticTicket;
1504
                    output->ticketLenAlloc = 0;
1505
                    output->ticketLen = 0;
1506
                }
1507
            }
1508
            else {
1509
                output->ticket = output->staticTicket;
1510
                output->ticketLenAlloc = 0;
1511
            }
1512
        }
1513
        else {
1514
            output->ticket = output->staticTicket;
1515
            output->ticketLenAlloc = 0;
1516
            output->ticketLen = 0;
1517
        }
1518
        if (error == WOLFSSL_SUCCESS) {
1519
            /* cppcheck-suppress uninitvar */
1520
            XMEMCPY(output->ticket, tmpTicket, output->ticketLen);
1521
        }
1522
    }
1523
    WC_FREE_VAR_EX(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER);
1524
1525
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
1526
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1527
    if (error == WOLFSSL_SUCCESS && preallocNonceUsed) {
1528
        if (preallocNonceLen < PREALLOC_SESSION_TICKET_NONCE_LEN) {
1529
            /* buffer bigger than needed */
1530
#ifndef XREALLOC
1531
            output->ticketNonce.data = (byte*)XMALLOC(preallocNonceLen,
1532
                output->heap, DYNAMIC_TYPE_SESSION_TICK);
1533
            if (output->ticketNonce.data != NULL)
1534
                XMEMCPY(output->ticketNonce.data, preallocNonce,
1535
                    preallocNonceLen);
1536
            XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK);
1537
            preallocNonce = NULL;
1538
#else
1539
            output->ticketNonce.data = (byte*)XREALLOC(preallocNonce,
1540
                preallocNonceLen, output->heap, DYNAMIC_TYPE_SESSION_TICK);
1541
            if (output->ticketNonce.data != NULL) {
1542
                /* don't free the reallocated pointer */
1543
                preallocNonce = NULL;
1544
            }
1545
#endif /* !XREALLOC */
1546
            if (output->ticketNonce.data == NULL) {
1547
                output->ticketNonce.data = output->ticketNonce.dataStatic;
1548
                output->ticketNonce.len = 0;
1549
                error = WOLFSSL_FAILURE;
1550
                /* preallocNonce will be free'd after the if */
1551
            }
1552
        }
1553
        else {
1554
            output->ticketNonce.data = preallocNonce;
1555
            output->ticketNonce.len = preallocNonceLen;
1556
            preallocNonce = NULL;
1557
        }
1558
    }
1559
    XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK);
1560
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
1561
1562
#endif
1563
1564
0
    return error;
1565
0
}
1566
1567
int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output)
1568
184
{
1569
184
    return GetSessionFromCache(ssl, output, 0);
1570
184
}
1571
1572
/* Lookup by the ID carried in a decrypted ticket without calling the
1573
 * external cache callback. */
1574
int wolfSSL_GetSessionFromInternalCache(WOLFSSL* ssl, WOLFSSL_SESSION* output)
1575
0
{
1576
0
    return GetSessionFromCache(ssl, output, 1);
1577
0
}
1578
1579
WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret,
1580
        byte restoreSessionCerts)
1581
184
{
1582
184
    WOLFSSL_SESSION* ret = NULL;
1583
1584
184
    (void)restoreSessionCerts; /* Kept for compatibility */
1585
1586
184
    if (wolfSSL_GetSessionFromCache(ssl, ssl->session) == WOLFSSL_SUCCESS) {
1587
0
        ret = ssl->session;
1588
0
    }
1589
184
    else {
1590
184
        WOLFSSL_MSG("wolfSSL_GetSessionFromCache did not return a session");
1591
184
    }
1592
1593
184
    if (ret != NULL && masterSecret != NULL)
1594
0
        XMEMCPY(masterSecret, ret->masterSecret, SECRET_LEN);
1595
1596
184
    return ret;
1597
184
}
1598
1599
int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session)
1600
0
{
1601
0
    SessionRow* sessRow = NULL;
1602
0
    int ret = WOLFSSL_SUCCESS;
1603
1604
0
    session = ClientSessionToSession(session);
1605
1606
0
    if (ssl == NULL || session == NULL || !session->isSetup) {
1607
0
        WOLFSSL_MSG("ssl or session NULL or not set up");
1608
0
        return WOLFSSL_FAILURE;
1609
0
    }
1610
1611
    /* We need to lock the session as the first step if its in the cache */
1612
0
    if (session->type == WOLFSSL_SESSION_TYPE_CACHE) {
1613
0
        if (session->cacheRow != INVALID_SESSION_ROW &&
1614
0
            session->cacheRow < SESSION_ROWS) {
1615
0
            sessRow = &SessionCache[session->cacheRow];
1616
0
            if (SESSION_ROW_RD_LOCK(sessRow) != 0) {
1617
0
                WOLFSSL_MSG("Session row lock failed");
1618
0
                return WOLFSSL_FAILURE;
1619
0
            }
1620
0
        }
1621
0
    }
1622
1623
0
    if (ret == WOLFSSL_SUCCESS && ssl->options.side != WOLFSSL_NEITHER_END &&
1624
0
            (byte)ssl->options.side != session->side) {
1625
0
        WOLFSSL_MSG("Setting session for wrong role");
1626
0
        ret = WOLFSSL_FAILURE;
1627
0
    }
1628
1629
0
    if (ret == WOLFSSL_SUCCESS) {
1630
0
        if (ssl->session == session) {
1631
0
            WOLFSSL_MSG("ssl->session and session same");
1632
0
        }
1633
0
        else if (session->type != WOLFSSL_SESSION_TYPE_CACHE) {
1634
0
            if (wolfSSL_SESSION_up_ref(session) == WOLFSSL_SUCCESS) {
1635
0
                wolfSSL_FreeSession(ssl->ctx, ssl->session);
1636
0
                ssl->session = session;
1637
0
            }
1638
0
            else
1639
0
                ret = WOLFSSL_FAILURE;
1640
0
        }
1641
0
        else {
1642
0
            ret = wolfSSL_DupSession(session, ssl->session, 0);
1643
0
            if (ret != WOLFSSL_SUCCESS)
1644
0
                WOLFSSL_MSG("Session duplicate failed");
1645
0
        }
1646
0
    }
1647
1648
    /* Let's copy over the altSessionID for local cache purposes */
1649
0
    if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID &&
1650
0
            ssl->session != session) {
1651
0
        ssl->session->haveAltSessionID = 1;
1652
0
        XMEMCPY(ssl->session->altSessionID, session->altSessionID, ID_LEN);
1653
0
    }
1654
1655
0
    if (sessRow != NULL) {
1656
0
        SESSION_ROW_UNLOCK(sessRow);
1657
0
        sessRow = NULL;
1658
0
    }
1659
1660
    /* Note: the `session` variable cannot be used below, since the row is
1661
     * un-locked */
1662
1663
0
    if (ret != WOLFSSL_SUCCESS)
1664
0
        return ret;
1665
1666
    /* A new session replaced the old one. Only resume it once it passes the
1667
     * checks below. */
1668
0
    ssl->options.resuming = 0;
1669
1670
#ifdef WOLFSSL_SESSION_ID_CTX
1671
    /* check for application context id */
1672
    if (ssl->sessionCtxSz > 0) {
1673
        if (XMEMCMP(ssl->sessionCtx, ssl->session->sessionCtx,
1674
                ssl->sessionCtxSz)) {
1675
            /* context id did not match! */
1676
            WOLFSSL_MSG("Session context did not match");
1677
            return WOLFSSL_FAILURE;
1678
        }
1679
    }
1680
#endif /* WOLFSSL_SESSION_ID_CTX */
1681
1682
0
    if (LowResTimer() >= (ssl->session->bornOn + ssl->session->timeout)) {
1683
0
#if !defined(OPENSSL_EXTRA) || !defined(WOLFSSL_ERROR_CODE_OPENSSL)
1684
0
        return WOLFSSL_FAILURE;  /* session timed out */
1685
#else /* defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL) */
1686
        /* Return success for OpenSSL compatibility but do not carry the
1687
         * expired session's version/cipher into ssl state, which would
1688
         * otherwise pin the ClientHello to stale values. */
1689
        WOLFSSL_MSG("Session is expired but return success for "
1690
                    "OpenSSL compatibility");
1691
        return WOLFSSL_SUCCESS;
1692
#endif
1693
0
    }
1694
0
    ssl->options.resuming = 1;
1695
0
#ifdef HAVE_EXTENDED_MASTER
1696
    /* A user EMS override takes precedence over the session's EMS state. */
1697
0
    if (ssl->options.requireEMS && ssl->options.side == WOLFSSL_CLIENT_END)
1698
0
        ssl->options.haveEMS = 1;
1699
0
    else if (ssl->options.disableEMS) {
1700
0
        ssl->options.haveEMS = 0;
1701
        /* An EMS session cannot be offered without the extension
1702
         * (RFC 7627 5.3): decline it, without adopting its version and
1703
         * cipher suite, and report the decline like the minDowngrade check
1704
         * below. TLS 1.3 sessions resume independently of EMS; their haveEMS
1705
         * is only the RFC 8446 Appendix D indicator. */
1706
0
        if (ssl->session->haveEMS &&
1707
0
                !IsAtLeastTLSv1_3(ssl->session->version)) {
1708
0
            ssl->options.resuming = 0;
1709
0
            return WOLFSSL_FAILURE;
1710
0
        }
1711
0
    }
1712
0
    else
1713
0
#endif
1714
0
    {
1715
0
        ssl->options.haveEMS = (ssl->session->haveEMS) ? 1 : 0;
1716
0
    }
1717
1718
0
    if (ssl->session->version.major != 0) {
1719
        /* Reject sessions whose protocol version is below the configured
1720
         * minimum so a stale cached session cannot make the client send a
1721
         * ClientHello advertising a version it isn't allowed to negotiate.
1722
         * DTLS minor versions are inverted: a higher minor means an older
1723
         * protocol, so the comparison flips. */
1724
0
        byte belowMinDowngrade;
1725
0
        if (ssl->options.dtls)
1726
0
            belowMinDowngrade = ssl->session->version.minor >
1727
0
                                ssl->options.minDowngrade;
1728
0
        else
1729
0
            belowMinDowngrade = ssl->session->version.minor <
1730
0
                                ssl->options.minDowngrade;
1731
0
        if (belowMinDowngrade) {
1732
0
            WOLFSSL_MSG("Session version below configured minDowngrade");
1733
0
            ssl->options.resuming = 0;
1734
0
            return WOLFSSL_FAILURE;
1735
0
        }
1736
0
        ssl->version              = ssl->session->version;
1737
0
        if (IsAtLeastTLSv1_3(ssl->version))
1738
0
            ssl->options.tls1_3 = 1;
1739
0
    }
1740
0
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
1741
0
                    (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
1742
0
    ssl->options.cipherSuite0 = ssl->session->cipherSuite0;
1743
0
    ssl->options.cipherSuite  = ssl->session->cipherSuite;
1744
0
#endif
1745
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
1746
    ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet;
1747
#endif
1748
1749
0
    return WOLFSSL_SUCCESS;
1750
0
}
1751
1752
1753
#ifdef WOLFSSL_SESSION_STATS
1754
static int get_locked_session_stats(word32* active, word32* total,
1755
                                    word32* peak);
1756
#endif
1757
1758
#ifndef NO_CLIENT_CACHE
1759
ClientSession* AddSessionToClientCache(int side, int row, int idx,
1760
    byte* serverID, word16 idLen, const byte* sessionID, word16 useTicket,
1761
    word32 cacheGen)
1762
0
{
1763
0
    int error = -1;
1764
0
    word32 clientRow = 0, clientIdx = 0;
1765
0
    ClientSession* ret = NULL;
1766
1767
0
    (void)useTicket;
1768
0
    if (side == WOLFSSL_CLIENT_END
1769
0
            && row != INVALID_SESSION_ROW
1770
0
            && (idLen
1771
#ifdef HAVE_SESSION_TICKET
1772
                || useTicket == 1
1773
#endif
1774
0
                || serverID != NULL
1775
0
                )) {
1776
1777
0
        WOLFSSL_MSG("Trying to add client cache entry");
1778
1779
0
        if (idLen) {
1780
0
            clientRow = HashObject(serverID,
1781
0
                    idLen, &error) % CLIENT_SESSION_ROWS;
1782
0
        }
1783
0
        else if (serverID != NULL) {
1784
0
            clientRow = HashObject(sessionID,
1785
0
                    ID_LEN, &error) % CLIENT_SESSION_ROWS;
1786
0
        }
1787
0
        else {
1788
0
            error = WOLFSSL_FATAL_ERROR;
1789
0
        }
1790
0
        if (error == 0 && wc_LockMutex(&clisession_mutex) == 0) {
1791
0
            clientIdx = (word32)ClientCache[clientRow].nextIdx;
1792
0
            if (clientIdx < CLIENT_SESSIONS_PER_ROW) {
1793
0
                ClientCache[clientRow].Clients[clientIdx].serverRow =
1794
0
                                                                (word16)row;
1795
0
                ClientCache[clientRow].Clients[clientIdx].serverIdx =
1796
0
                                                                (word16)idx;
1797
0
                ClientCache[clientRow].Clients[clientIdx].cacheGen = cacheGen;
1798
0
                if (sessionID != NULL) {
1799
0
                    word32 sessionIDHash = HashObject(sessionID, ID_LEN,
1800
0
                                                      &error);
1801
0
                    if (error == 0) {
1802
0
                        ClientCache[clientRow].Clients[clientIdx].sessionIDHash
1803
0
                            = sessionIDHash;
1804
0
                    }
1805
0
                }
1806
0
            }
1807
0
            else {
1808
0
                error = WOLFSSL_FATAL_ERROR;
1809
0
                ClientCache[clientRow].nextIdx = 0; /* reset index as safety */
1810
0
                WOLFSSL_MSG("Invalid client cache index! "
1811
0
                            "Possible corrupted memory");
1812
0
            }
1813
0
            if (error == 0) {
1814
0
                WOLFSSL_MSG("Adding client cache entry");
1815
1816
0
                ret = &ClientCache[clientRow].Clients[clientIdx];
1817
1818
0
                if (ClientCache[clientRow].totalCount < CLIENT_SESSIONS_PER_ROW)
1819
0
                    ClientCache[clientRow].totalCount++;
1820
0
                ClientCache[clientRow].nextIdx++;
1821
0
                ClientCache[clientRow].nextIdx %= CLIENT_SESSIONS_PER_ROW;
1822
0
            }
1823
1824
0
            wc_UnLockMutex(&clisession_mutex);
1825
0
        }
1826
0
        else {
1827
0
            WOLFSSL_MSG("Hash session or lock failed");
1828
0
        }
1829
0
    }
1830
0
    else {
1831
0
        WOLFSSL_MSG("Skipping client cache");
1832
0
    }
1833
1834
0
    return ret;
1835
0
}
1836
#endif /* !NO_CLIENT_CACHE */
1837
1838
/* As ClientSessionToSession(), but when the handle named an entry in the
1839
 * client cache its row is left read-locked and returned in lockedRow. The
1840
 * caller reads the members it needs and then releases the row, so the entry
1841
 * cannot be replaced or freed in between. */
1842
static WOLFSSL_SESSION* ClientSessionToSessionRdLocked(
1843
    const WOLFSSL_SESSION* session, SessionRow** lockedRow)
1844
50.1k
{
1845
50.1k
    WOLFSSL_ENTER("ClientSessionToSession");
1846
50.1k
    *lockedRow = NULL;
1847
50.1k
#ifdef NO_SESSION_CACHE_REF
1848
50.1k
    return (WOLFSSL_SESSION*)session;
1849
#else
1850
#ifndef NO_CLIENT_CACHE
1851
    if (session == NULL)
1852
        return NULL;
1853
    /* Check if session points into ClientCache */
1854
    if ((byte*)session >= (byte*)ClientCache &&
1855
            /* Cast to byte* to make pointer arithmetic work per byte */
1856
            (byte*)session < ((byte*)ClientCache) + sizeof(ClientCache)) {
1857
        ClientSession* clientSession = (ClientSession*)session;
1858
        SessionRow* sessRow = NULL;
1859
        WOLFSSL_SESSION* cacheSession = NULL;
1860
        word32 sessionIDHash = 0;
1861
        int error = 0;
1862
        session = NULL; /* Default to NULL for failure case */
1863
        if (wc_LockMutex(&clisession_mutex) != 0) {
1864
            WOLFSSL_MSG("Client cache mutex lock failed");
1865
            return NULL;
1866
        }
1867
        if (clientSession->serverRow >= SESSION_ROWS ||
1868
                clientSession->serverIdx >= SESSIONS_PER_ROW) {
1869
            WOLFSSL_MSG("Client cache serverRow or serverIdx invalid");
1870
            error = WOLFSSL_FATAL_ERROR;
1871
        }
1872
        if (error == 0) {
1873
            /* Lock row */
1874
            sessRow = &SessionCache[clientSession->serverRow];
1875
            /* Prevent memory access before clientSession->serverRow and
1876
             * clientSession->serverIdx are sanitized. */
1877
            XFENCE();
1878
            error = SESSION_ROW_RD_LOCK(sessRow);
1879
            if (error != 0) {
1880
                WOLFSSL_MSG("Session cache row lock failure");
1881
                sessRow = NULL;
1882
            }
1883
        }
1884
        if (error == 0) {
1885
#ifdef SESSION_CACHE_DYNAMIC_MEM
1886
            cacheSession = sessRow->Sessions[clientSession->serverIdx];
1887
#else
1888
            cacheSession = &sessRow->Sessions[clientSession->serverIdx];
1889
#endif
1890
            /* Prevent memory access */
1891
            XFENCE();
1892
            if (cacheSession == NULL || cacheSession->sessionIDSz == 0) {
1893
                cacheSession = NULL;
1894
                WOLFSSL_MSG("Session cache entry not set");
1895
                error = WOLFSSL_FATAL_ERROR;
1896
            }
1897
        }
1898
        if (error == 0) {
1899
            /* Calculate the hash of the session ID */
1900
            sessionIDHash = HashObject(cacheSession->sessionID, ID_LEN,
1901
                    &error);
1902
        }
1903
        if (error == 0) {
1904
            /* Check the session ID hash matches */
1905
            error = clientSession->sessionIDHash != sessionIDHash;
1906
            if (error != 0)
1907
                WOLFSSL_MSG("session ID hashes don't match");
1908
        }
1909
        if (error == 0) {
1910
            /* The peer picks the session ID, so a matching hash only says the
1911
             * entry carries that ID, not that it still holds this session. */
1912
            error = clientSession->cacheGen != cacheSession->cacheGen;
1913
            if (error != 0)
1914
                WOLFSSL_MSG("session cache entry was overwritten");
1915
        }
1916
        if (error == 0) {
1917
            /* Hashes match */
1918
            session = cacheSession;
1919
            WOLFSSL_MSG("Found session cache matching client session object");
1920
        }
1921
        if (sessRow != NULL) {
1922
            if (session != NULL) {
1923
                *lockedRow = sessRow;
1924
            }
1925
            else {
1926
                SESSION_ROW_UNLOCK(sessRow);
1927
            }
1928
        }
1929
        wc_UnLockMutex(&clisession_mutex);
1930
        return (WOLFSSL_SESSION*)session;
1931
    }
1932
    else {
1933
        /* Plain WOLFSSL_SESSION object */
1934
        return (WOLFSSL_SESSION*)session;
1935
    }
1936
#else
1937
    return (WOLFSSL_SESSION*)session;
1938
#endif
1939
#endif
1940
50.1k
}
1941
1942
/**
1943
 * For backwards compatibility, this API needs to be used in *ALL* functions
1944
 * that access the WOLFSSL_SESSION members directly.
1945
 *
1946
 * This API checks if the passed in session is actually a ClientSession object
1947
 * and returns the matching session cache object. Otherwise just return the
1948
 * input. ClientSession objects only occur in the ClientCache. They are not
1949
 * allocated anywhere else.
1950
 */
1951
WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session)
1952
50.1k
{
1953
50.1k
    SessionRow* sessRow = NULL;
1954
50.1k
    WOLFSSL_SESSION* ret;
1955
1956
50.1k
    ret = ClientSessionToSessionRdLocked(session, &sessRow);
1957
50.1k
    if (sessRow != NULL) {
1958
0
        SESSION_ROW_UNLOCK(sessRow);
1959
0
    }
1960
1961
50.1k
    return ret;
1962
50.1k
}
1963
1964
int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession,
1965
        const byte* id, byte idSz, int* sessionIndex, int side,
1966
        word16 useTicket, ClientSession** clientCacheEntry)
1967
0
{
1968
0
    WOLFSSL_SESSION* cacheSession = NULL;
1969
0
    SessionRow* sessRow = NULL;
1970
0
    word32 idx = 0;
1971
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
1972
    WOLFSSL_X509* cachePeer = NULL;
1973
    WOLFSSL_X509* addPeer = NULL;
1974
#endif
1975
#ifdef HAVE_SESSION_TICKET
1976
    byte*  cacheTicBuff = NULL;
1977
    byte   ticBuffUsed = 0;
1978
    byte*  ticBuff = NULL;
1979
    int    ticLen  = 0;
1980
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
1981
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1982
    byte *preallocNonce = NULL;
1983
    byte preallocNonceLen = 0;
1984
    byte preallocNonceUsed = 0;
1985
    byte *toFree = NULL;
1986
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC */
1987
#endif /* HAVE_SESSION_TICKET */
1988
0
    int ret = 0;
1989
0
    int row;
1990
0
    int i;
1991
0
    int overwrite = 0;
1992
0
    word32 cacheGen = 0;
1993
0
    (void)ctx;
1994
0
    (void)sessionIndex;
1995
0
    (void)useTicket;
1996
0
    (void)clientCacheEntry;
1997
0
    (void)cacheGen;
1998
1999
0
    WOLFSSL_ENTER("AddSessionToCache");
2000
2001
0
    if (idSz == 0) {
2002
0
        WOLFSSL_MSG("AddSessionToCache idSz == 0");
2003
0
        return BAD_FUNC_ARG;
2004
0
    }
2005
2006
0
    addSession = ClientSessionToSession(addSession);
2007
0
    if (addSession == NULL) {
2008
0
        WOLFSSL_MSG("AddSessionToCache is NULL");
2009
0
        return MEMORY_E;
2010
0
    }
2011
2012
#ifdef HAVE_SESSION_TICKET
2013
    ticLen = addSession->ticketLen;
2014
    /* Alloc Memory here to avoid syscalls during lock */
2015
    if (ticLen > SESSION_TICKET_LEN) {
2016
        ticBuff = (byte*)XMALLOC((size_t)ticLen, NULL,
2017
                DYNAMIC_TYPE_SESSION_TICK);
2018
        if (ticBuff == NULL) {
2019
            return MEMORY_E;
2020
        }
2021
    }
2022
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
2023
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2024
    if (addSession->ticketNonce.data != addSession->ticketNonce.dataStatic) {
2025
        /* Cache entries carry no heap hint and are always freed with NULL. */
2026
        preallocNonce = (byte*)XMALLOC(addSession->ticketNonce.len, NULL,
2027
            DYNAMIC_TYPE_SESSION_TICK);
2028
        if (preallocNonce == NULL) {
2029
            XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2030
            return MEMORY_E;
2031
        }
2032
        preallocNonceLen = addSession->ticketNonce.len;
2033
    }
2034
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
2035
#endif /* HAVE_SESSION_TICKET */
2036
2037
    /* Find a position for the new session in cache and use that */
2038
    /* Use the session object in the cache for external cache if required */
2039
0
    row = (int)SessionCacheRow(id, side, &ret);
2040
0
    if (ret != 0) {
2041
0
        WOLFSSL_MSG("Hash session failed");
2042
    #ifdef HAVE_SESSION_TICKET
2043
        XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2044
    #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&      \
2045
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2046
        XFREE(preallocNonce, NULL, DYNAMIC_TYPE_SESSION_TICK);
2047
    #endif
2048
    #endif
2049
0
        return ret;
2050
0
    }
2051
2052
0
    sessRow = &SessionCache[row];
2053
0
    if (SESSION_ROW_WR_LOCK(sessRow) != 0) {
2054
    #ifdef HAVE_SESSION_TICKET
2055
        XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2056
    #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
2057
        (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && \
2058
                                 FIPS_VERSION_GE(5,3)))
2059
        XFREE(preallocNonce, NULL, DYNAMIC_TYPE_SESSION_TICK);
2060
    #endif
2061
    #endif
2062
0
        WOLFSSL_MSG("Session row lock failed");
2063
0
        return BAD_MUTEX_E;
2064
0
    }
2065
2066
0
    for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) {
2067
    #ifdef SESSION_CACHE_DYNAMIC_MEM
2068
        cacheSession = sessRow->Sessions[i];
2069
    #else
2070
0
        cacheSession = &sessRow->Sessions[i];
2071
0
    #endif
2072
0
        if (cacheSession && XMEMCMP(id,
2073
0
                cacheSession->sessionID, ID_LEN) == 0 &&
2074
0
                cacheSession->side == side) {
2075
0
            WOLFSSL_MSG("Session already exists. Overwriting.");
2076
0
            overwrite = 1;
2077
0
            idx = (word32)i;
2078
0
            break;
2079
0
        }
2080
0
    }
2081
2082
0
    if (!overwrite)
2083
0
        idx = (word32)sessRow->nextIdx;
2084
2085
0
    if (idx >= SESSIONS_PER_ROW) {
2086
        /* bad index, possible corrupted session cache memory.
2087
         * reset index to a safe value, unlock the row, and return error. */
2088
    #ifdef HAVE_SESSION_TICKET
2089
        XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2090
    #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&      \
2091
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2092
        XFREE(preallocNonce, NULL, DYNAMIC_TYPE_SESSION_TICK);
2093
    #endif
2094
    #endif
2095
0
        WOLFSSL_MSG_EX("Invalid session cache index: %d", idx);
2096
0
        sessRow->nextIdx = 0;
2097
0
        SESSION_ROW_UNLOCK(sessRow);
2098
0
        return MEMORY_E;
2099
0
    }
2100
#ifdef SESSION_INDEX
2101
    if (sessionIndex != NULL)
2102
        *sessionIndex = (row << SESSIDX_ROW_SHIFT) | idx;
2103
#endif
2104
2105
#ifdef SESSION_CACHE_DYNAMIC_MEM
2106
    cacheSession = sessRow->Sessions[idx];
2107
    if (cacheSession == NULL) {
2108
        cacheSession = (WOLFSSL_SESSION*) XMALLOC(sizeof(WOLFSSL_SESSION),
2109
                                         sessRow->heap, DYNAMIC_TYPE_SESSION);
2110
        if (cacheSession == NULL) {
2111
        #ifdef HAVE_SESSION_TICKET
2112
            XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2113
        #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
2114
            (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && \
2115
                                     FIPS_VERSION_GE(5,3)))
2116
            XFREE(preallocNonce, NULL, DYNAMIC_TYPE_SESSION_TICK);
2117
        #endif
2118
        #endif
2119
            SESSION_ROW_UNLOCK(sessRow);
2120
            return MEMORY_E;
2121
        }
2122
        XMEMSET(cacheSession, 0, sizeof(WOLFSSL_SESSION));
2123
        sessRow->Sessions[idx] = cacheSession;
2124
    }
2125
#else
2126
0
    cacheSession = &sessRow->Sessions[idx];
2127
0
#endif
2128
2129
#ifdef HAVE_EX_DATA_CRYPTO
2130
    if (overwrite) {
2131
        /* Figure out who owns the ex_data */
2132
        if (cacheSession->ownExData) {
2133
            /* Prioritize cacheSession copy */
2134
            XMEMCPY(&addSession->ex_data, &cacheSession->ex_data,
2135
                    sizeof(WOLFSSL_CRYPTO_EX_DATA));
2136
        }
2137
        /* else will be copied in wolfSSL_DupSession call */
2138
    }
2139
    else if (cacheSession->ownExData) {
2140
        crypto_ex_cb_free_data(cacheSession, crypto_ex_cb_ctx_session,
2141
                               &cacheSession->ex_data);
2142
        cacheSession->ownExData = 0;
2143
    }
2144
#endif
2145
2146
0
    if (!overwrite)
2147
0
        EvictSessionFromCache(cacheSession);
2148
2149
0
    cacheSession->type = WOLFSSL_SESSION_TYPE_CACHE;
2150
0
    cacheSession->cacheRow = row;
2151
    /* Only a re-add of the same session keeps existing references to this
2152
     * entry valid; any other write, same session ID or not, invalidates them. */
2153
0
    if (!overwrite || ConstantCompare(cacheSession->masterSecret,
2154
0
            addSession->masterSecret, SECRET_LEN) != 0)
2155
0
        cacheSession->cacheGen = ++sessRow->cacheGen;
2156
0
    cacheGen = cacheSession->cacheGen;
2157
2158
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
2159
    /* Save the peer field to free after unlocking the row */
2160
    if (cacheSession->peer != NULL)
2161
        cachePeer = cacheSession->peer;
2162
    cacheSession->peer = NULL;
2163
#endif
2164
#ifdef HAVE_SESSION_TICKET
2165
    /* If we can reuse the existing buffer in cacheSession then we won't touch
2166
     * ticBuff at all making it a very cheap malloc/free. The page on a modern
2167
     * OS will most likely not even be allocated to the process. */
2168
    if (ticBuff != NULL && cacheSession->ticketLenAlloc < ticLen) {
2169
        /* Save pointer only if separately allocated */
2170
        if (cacheSession->ticket != cacheSession->staticTicket)
2171
            cacheTicBuff = cacheSession->ticket;
2172
        ticBuffUsed = 1;
2173
        cacheSession->ticket = ticBuff;
2174
        cacheSession->ticketLenAlloc = (word16) ticLen;
2175
    }
2176
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
2177
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2178
    /* cache entry never used */
2179
    if (cacheSession->ticketNonce.data == NULL)
2180
        cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic;
2181
2182
    if (cacheSession->ticketNonce.data !=
2183
            cacheSession->ticketNonce.dataStatic) {
2184
        toFree = cacheSession->ticketNonce.data;
2185
        cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic;
2186
        cacheSession->ticketNonce.len = 0;
2187
    }
2188
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
2189
#endif
2190
#ifdef SESSION_CERTS
2191
    if (overwrite &&
2192
            addSession->chain.count == 0 &&
2193
            cacheSession->chain.count > 0) {
2194
        /* Copy in the certs from the session */
2195
        addSession->chain.count = cacheSession->chain.count;
2196
        XMEMCPY(addSession->chain.certs, cacheSession->chain.certs,
2197
                sizeof(x509_buffer) * (size_t)cacheSession->chain.count);
2198
    }
2199
#endif /* SESSION_CERTS */
2200
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
2201
    /* Don't copy the peer cert into cache */
2202
    addPeer = addSession->peer;
2203
    addSession->peer = NULL;
2204
#endif
2205
0
    cacheSession->heap = NULL;
2206
    /* Copy data into the cache object */
2207
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) &&                  \
2208
    defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                   \
2209
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2210
    ret = (wolfSSL_DupSessionEx(addSession, cacheSession, 1, 1, preallocNonce,
2211
                                &preallocNonceLen, &preallocNonceUsed)
2212
           == WC_NO_ERR_TRACE(WOLFSSL_FAILURE));
2213
#else
2214
0
    ret = (wolfSSL_DupSession(addSession, cacheSession, 1)
2215
0
           == WC_NO_ERR_TRACE(WOLFSSL_FAILURE));
2216
0
#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC
2217
          && FIPS_VERSION_GE(5,3)*/
2218
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
2219
    addSession->peer = addPeer;
2220
#endif
2221
2222
0
    if (ret == 0) {
2223
0
        if (!overwrite) {
2224
            /* Increment the totalCount and the nextIdx */
2225
0
            if (sessRow->totalCount < SESSIONS_PER_ROW)
2226
0
                sessRow->totalCount++;
2227
0
            sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW;
2228
0
        }
2229
0
        if (id != addSession->sessionID) {
2230
            /* ssl->session->sessionID may contain the bogus ID or we want the
2231
             * ID from the arrays object */
2232
0
            XMEMCPY(cacheSession->sessionID, id, ID_LEN);
2233
0
            cacheSession->sessionIDSz = ID_LEN;
2234
0
        }
2235
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
2236
        if (ctx->rem_sess_cb != NULL)
2237
            cacheSession->rem_sess_cb = ctx->rem_sess_cb;
2238
#endif
2239
#ifdef HAVE_EX_DATA
2240
        /* The session in cache now owns the ex_data */
2241
        addSession->ownExData = 0;
2242
        cacheSession->ownExData = 1;
2243
#endif
2244
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) &&                  \
2245
    defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
2246
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2247
        if (preallocNonce != NULL && preallocNonceUsed) {
2248
            cacheSession->ticketNonce.data = preallocNonce;
2249
            cacheSession->ticketNonce.len = preallocNonceLen;
2250
            preallocNonce = NULL;
2251
            preallocNonceLen = 0;
2252
        }
2253
#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC
2254
        * && FIPS_VERSION_GE(5,3)*/
2255
0
    }
2256
#ifdef HAVE_SESSION_TICKET
2257
    else if (ticBuffUsed) {
2258
        /* Error occurred. Need to clean up the ticket buffer. */
2259
        cacheSession->ticket = cacheSession->staticTicket;
2260
        cacheSession->ticketLenAlloc = 0;
2261
        cacheSession->ticketLen = 0;
2262
    }
2263
#endif
2264
0
    SESSION_ROW_UNLOCK(sessRow);
2265
0
    cacheSession = NULL; /* Can't access after unlocked */
2266
2267
0
#ifndef NO_CLIENT_CACHE
2268
0
    if (ret == 0 && clientCacheEntry != NULL) {
2269
0
        ClientSession* clientCache = AddSessionToClientCache(side, row,
2270
0
            (int)idx, addSession->serverID, addSession->idLen, id, useTicket,
2271
0
            cacheGen);
2272
0
        if (clientCache != NULL)
2273
0
            *clientCacheEntry = clientCache;
2274
0
    }
2275
0
#endif
2276
2277
#ifdef HAVE_SESSION_TICKET
2278
    if (ticBuff != NULL && !ticBuffUsed)
2279
        XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2280
    XFREE(cacheTicBuff, NULL, DYNAMIC_TYPE_SESSION_TICK);
2281
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&         \
2282
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
2283
    XFREE(preallocNonce, NULL, DYNAMIC_TYPE_SESSION_TICK);
2284
    XFREE(toFree, NULL, DYNAMIC_TYPE_SESSION_TICK);
2285
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
2286
#endif
2287
2288
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
2289
    if (cachePeer != NULL) {
2290
        wolfSSL_X509_free(cachePeer);
2291
        cachePeer = NULL; /* Make sure not use after this point */
2292
    }
2293
#endif
2294
2295
0
    return ret;
2296
0
}
2297
2298
void AddSession(WOLFSSL* ssl)
2299
0
{
2300
0
    int    error = 0;
2301
0
    const byte* id = NULL;
2302
0
    byte idSz = 0;
2303
0
    WOLFSSL_SESSION* session = ssl->session;
2304
2305
0
    (void)error;
2306
2307
0
    WOLFSSL_ENTER("AddSession");
2308
2309
0
    if (SslSessionCacheOff(ssl, session)) {
2310
0
        WOLFSSL_MSG("Cache off");
2311
0
        return;
2312
0
    }
2313
2314
0
    if (session->haveAltSessionID) {
2315
0
        id = session->altSessionID;
2316
0
        idSz = ID_LEN;
2317
0
    }
2318
0
    else {
2319
0
        id = session->sessionID;
2320
0
        idSz = session->sessionIDSz;
2321
0
    }
2322
2323
    /* Do this only for the client because if the server doesn't have an ID at
2324
     * this point, it won't on resumption. */
2325
0
    if (idSz == 0 && ssl->options.side == WOLFSSL_CLIENT_END) {
2326
0
        WC_RNG* rng = NULL;
2327
0
        int genRet;
2328
#if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA)
2329
        int rngLocked = 0;
2330
#endif
2331
0
        if (ssl->rng != NULL)
2332
0
            rng = ssl->rng;
2333
#if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA)
2334
        else if (initGlobalRNG == 1 || wolfSSL_RAND_Init() == WOLFSSL_SUCCESS) {
2335
            /* Global RNG is shared, lock it while generating. */
2336
            if (wc_LockMutex(&globalRNGMutex) != 0) {
2337
                WOLFSSL_MSG("Bad Lock Mutex rng");
2338
                return;
2339
            }
2340
            rng = &globalRNG;
2341
            rngLocked = 1;
2342
        }
2343
#endif
2344
0
        genRet = wc_RNG_GenerateBlock(rng, ssl->session->altSessionID, ID_LEN);
2345
#if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA)
2346
        if (rngLocked)
2347
            wc_UnLockMutex(&globalRNGMutex);
2348
#endif
2349
0
        if (genRet != 0)
2350
0
            return;
2351
0
        ssl->session->haveAltSessionID = 1;
2352
0
        id = ssl->session->altSessionID;
2353
0
        idSz = ID_LEN;
2354
0
    }
2355
2356
#ifdef HAVE_EXT_CACHE
2357
    if (!ssl->options.internalCacheOff)
2358
#endif
2359
0
    {
2360
        /* Try to add the session to internal cache or external cache
2361
        if a new_sess_cb is set. Its ok if we don't succeed. */
2362
0
        (void)AddSessionToCache(ssl->ctx, session, id, idSz,
2363
#ifdef SESSION_INDEX
2364
                &ssl->sessionIndex,
2365
#else
2366
0
                NULL,
2367
0
#endif
2368
0
                ssl->options.side,
2369
#ifdef HAVE_SESSION_TICKET
2370
                ssl->options.useTicket,
2371
#else
2372
0
                0,
2373
0
#endif
2374
0
#ifndef NO_CLIENT_CACHE
2375
0
                (ssl->options.side == WOLFSSL_CLIENT_END) ?
2376
0
                        &ssl->clientSession : NULL
2377
#else
2378
                NULL
2379
#endif
2380
0
                        );
2381
0
    }
2382
2383
#ifdef HAVE_EXT_CACHE
2384
    if (error == 0 && ssl->ctx->new_sess_cb != NULL) {
2385
        int cbRet = 0;
2386
        wolfSSL_SESSION_up_ref(session);
2387
        cbRet = ssl->ctx->new_sess_cb(ssl, session);
2388
        if (cbRet == 0)
2389
            wolfSSL_FreeSession(ssl->ctx, session);
2390
    }
2391
#endif
2392
2393
#if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS)
2394
    if (error == 0) {
2395
        word32 active = 0;
2396
2397
        error = get_locked_session_stats(&active, NULL, NULL);
2398
        if (error == WOLFSSL_SUCCESS) {
2399
            error = 0;  /* back to this function ok */
2400
2401
            if (PeakSessions < active) {
2402
                PeakSessions = active;
2403
            }
2404
        }
2405
    }
2406
#endif /* WOLFSSL_SESSION_STATS && WOLFSSL_PEAK_SESSIONS */
2407
0
    (void)error;
2408
0
}
2409
2410
2411
#ifdef SESSION_INDEX
2412
2413
int wolfSSL_GetSessionIndex(WOLFSSL* ssl)
2414
{
2415
    WOLFSSL_ENTER("wolfSSL_GetSessionIndex");
2416
    WOLFSSL_LEAVE("wolfSSL_GetSessionIndex", ssl->sessionIndex);
2417
    return ssl->sessionIndex;
2418
}
2419
2420
2421
int wolfSSL_GetSessionAtIndex(int idx, WOLFSSL_SESSION* session)
2422
{
2423
    int row, col, result = WOLFSSL_FAILURE;
2424
    SessionRow* sessRow;
2425
    WOLFSSL_SESSION* cacheSession;
2426
2427
    WOLFSSL_ENTER("wolfSSL_GetSessionAtIndex");
2428
2429
    session = ClientSessionToSession(session);
2430
2431
    row = idx >> SESSIDX_ROW_SHIFT;
2432
    col = idx & SESSIDX_IDX_MASK;
2433
2434
    if (session == NULL ||
2435
            row < 0 || row >= SESSION_ROWS || col >= SESSIONS_PER_ROW) {
2436
        return WOLFSSL_FAILURE;
2437
    }
2438
2439
    sessRow = &SessionCache[row];
2440
    if (SESSION_ROW_RD_LOCK(sessRow) != 0) {
2441
        return BAD_MUTEX_E;
2442
    }
2443
2444
#ifdef SESSION_CACHE_DYNAMIC_MEM
2445
    cacheSession = sessRow->Sessions[col];
2446
#else
2447
    cacheSession = &sessRow->Sessions[col];
2448
#endif
2449
    if (cacheSession) {
2450
        /* Must not alias the ticket, peer cert and ex_data the cache owns and
2451
         * frees on overwrite or eviction. The caller keeps this copy, so it
2452
         * does not take over the cache's ex_data either. */
2453
        result = wolfSSL_DupSessionEx(cacheSession, session, 0, 0, NULL, NULL,
2454
            NULL);
2455
    }
2456
    else {
2457
        result = WOLFSSL_FAILURE;
2458
    }
2459
2460
    SESSION_ROW_UNLOCK(sessRow);
2461
2462
    WOLFSSL_LEAVE("wolfSSL_GetSessionAtIndex", result);
2463
    return result;
2464
}
2465
2466
#endif /* SESSION_INDEX */
2467
2468
#if defined(SESSION_CERTS)
2469
2470
WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session)
2471
{
2472
    WOLFSSL_X509_CHAIN* chain = NULL;
2473
2474
    WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain");
2475
2476
    session = ClientSessionToSession(session);
2477
2478
    if (session)
2479
        chain = &session->chain;
2480
2481
    WOLFSSL_LEAVE("wolfSSL_SESSION_get_peer_chain", chain ? 1 : 0);
2482
    return chain;
2483
}
2484
2485
2486
#ifdef OPENSSL_EXTRA
2487
/* gets the peer certificate associated with the session passed in
2488
 * returns null on failure, the caller should not free the returned pointer */
2489
WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session)
2490
{
2491
    WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain");
2492
2493
    session = ClientSessionToSession(session);
2494
    if (session) {
2495
        int count;
2496
2497
        count = wolfSSL_get_chain_count(&session->chain);
2498
        if (count < 1 || count > MAX_CHAIN_DEPTH) {
2499
            WOLFSSL_MSG("bad count found");
2500
            return NULL;
2501
        }
2502
2503
        if (session->peer == NULL) {
2504
            session->peer = wolfSSL_get_chain_X509(&session->chain, 0);
2505
        }
2506
        return session->peer;
2507
    }
2508
    WOLFSSL_MSG("No session passed in");
2509
2510
    return NULL;
2511
}
2512
#endif /* OPENSSL_EXTRA */
2513
#endif /* SESSION_INDEX && SESSION_CERTS */
2514
2515
2516
#ifdef WOLFSSL_SESSION_STATS
2517
2518
static int get_locked_session_stats(word32* active, word32* total, word32* peak)
2519
{
2520
    int result = WOLFSSL_SUCCESS;
2521
    int i;
2522
    int count;
2523
    int idx;
2524
    word32 now   = 0;
2525
    word32 seen  = 0;
2526
    word32 ticks = LowResTimer();
2527
2528
    WOLFSSL_ENTER("get_locked_session_stats");
2529
2530
#ifndef ENABLE_SESSION_CACHE_ROW_LOCK
2531
    SESSION_ROW_RD_LOCK(&SessionCache[0]);
2532
#endif
2533
    for (i = 0; i < SESSION_ROWS; i++) {
2534
        SessionRow* row = &SessionCache[i];
2535
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
2536
        if (SESSION_ROW_RD_LOCK(row) != 0) {
2537
            WOLFSSL_MSG("Session row cache mutex lock failed");
2538
            return BAD_MUTEX_E;
2539
        }
2540
    #endif
2541
2542
        seen += row->totalCount;
2543
2544
        if (active == NULL) {
2545
            SESSION_ROW_UNLOCK(row);
2546
            continue;
2547
        }
2548
2549
        count = min((word32)row->totalCount, SESSIONS_PER_ROW);
2550
        idx   = row->nextIdx - 1;
2551
        if (idx < 0 || idx >= SESSIONS_PER_ROW) {
2552
            idx = SESSIONS_PER_ROW - 1; /* if back to front previous was end */
2553
        }
2554
2555
        for (; count > 0; --count) {
2556
            /* if not expired then good */
2557
#ifdef SESSION_CACHE_DYNAMIC_MEM
2558
            if (row->Sessions[idx] &&
2559
                ticks < (row->Sessions[idx]->bornOn +
2560
                            row->Sessions[idx]->timeout) )
2561
#else
2562
            if (ticks < (row->Sessions[idx].bornOn +
2563
                            row->Sessions[idx].timeout) )
2564
#endif
2565
            {
2566
                now++;
2567
            }
2568
2569
            idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1;
2570
        }
2571
2572
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
2573
        SESSION_ROW_UNLOCK(row);
2574
    #endif
2575
    }
2576
#ifndef ENABLE_SESSION_CACHE_ROW_LOCK
2577
    SESSION_ROW_UNLOCK(&SessionCache[0]);
2578
#endif
2579
2580
    if (active) {
2581
        *active = now;
2582
    }
2583
    if (total) {
2584
        *total = seen;
2585
    }
2586
2587
#ifdef WOLFSSL_PEAK_SESSIONS
2588
    if (peak) {
2589
        *peak = PeakSessions;
2590
    }
2591
#else
2592
    (void)peak;
2593
#endif
2594
2595
    WOLFSSL_LEAVE("get_locked_session_stats", result);
2596
2597
    return result;
2598
}
2599
2600
2601
/* return WOLFSSL_SUCCESS on ok */
2602
int wolfSSL_get_session_stats(word32* active, word32* total, word32* peak,
2603
                              word32* maxSessions)
2604
{
2605
    int result = WOLFSSL_SUCCESS;
2606
2607
    WOLFSSL_ENTER("wolfSSL_get_session_stats");
2608
2609
    if (maxSessions) {
2610
        *maxSessions = SESSIONS_PER_ROW * SESSION_ROWS;
2611
2612
        if (active == NULL && total == NULL && peak == NULL)
2613
            return result;  /* we're done */
2614
    }
2615
2616
    /* user must provide at least one query value */
2617
    if (active == NULL && total == NULL && peak == NULL) {
2618
        return BAD_FUNC_ARG;
2619
    }
2620
2621
    result = get_locked_session_stats(active, total, peak);
2622
2623
    WOLFSSL_LEAVE("wolfSSL_get_session_stats", result);
2624
2625
    return result;
2626
}
2627
2628
#endif /* WOLFSSL_SESSION_STATS */
2629
2630
2631
    #ifdef PRINT_SESSION_STATS
2632
2633
    /* WOLFSSL_SUCCESS on ok */
2634
    int wolfSSL_PrintSessionStats(void)
2635
    {
2636
        word32 totalSessionsSeen = 0;
2637
        word32 totalSessionsNow = 0;
2638
        word32 peak = 0;
2639
        word32 maxSessions = 0;
2640
        int    i;
2641
        int    ret;
2642
        double E;               /* expected freq */
2643
        double chiSquare = 0;
2644
2645
        ret = wolfSSL_get_session_stats(&totalSessionsNow, &totalSessionsSeen,
2646
                                        &peak, &maxSessions);
2647
        if (ret != WOLFSSL_SUCCESS)
2648
            return ret;
2649
        printf("Total Sessions Seen = %u\n", totalSessionsSeen);
2650
        printf("Total Sessions Now  = %u\n", totalSessionsNow);
2651
#ifdef WOLFSSL_PEAK_SESSIONS
2652
        printf("Peak  Sessions      = %u\n", peak);
2653
#endif
2654
        printf("Max   Sessions      = %u\n", maxSessions);
2655
2656
        E = (double)totalSessionsSeen / SESSION_ROWS;
2657
2658
        for (i = 0; i < SESSION_ROWS; i++) {
2659
            double diff = SessionCache[i].totalCount - E;
2660
            diff *= diff;                /* square    */
2661
            diff /= E;                   /* normalize */
2662
2663
            chiSquare += diff;
2664
        }
2665
        printf("  chi-square = %5.1f, d.f. = %d\n", chiSquare,
2666
                                                     SESSION_ROWS - 1);
2667
        #if (SESSION_ROWS == 11)
2668
            printf(" .05 p value =  18.3, chi-square should be less\n");
2669
        #elif (SESSION_ROWS == 211)
2670
            printf(".05 p value  = 244.8, chi-square should be less\n");
2671
        #elif (SESSION_ROWS == 5981)
2672
            printf(".05 p value  = 6161.0, chi-square should be less\n");
2673
        #elif (SESSION_ROWS == 3)
2674
            printf(".05 p value  =   6.0, chi-square should be less\n");
2675
        #elif (SESSION_ROWS == 2861)
2676
            printf(".05 p value  = 2985.5, chi-square should be less\n");
2677
        #endif
2678
        printf("\n");
2679
2680
        return ret;
2681
    }
2682
2683
    #endif /* SESSION_STATS */
2684
2685
#else  /* NO_SESSION_CACHE */
2686
2687
WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session)
2688
{
2689
    return (WOLFSSL_SESSION*)session;
2690
}
2691
2692
/* No session cache version */
2693
WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret,
2694
        byte restoreSessionCerts)
2695
{
2696
    (void)ssl;
2697
    (void)masterSecret;
2698
    (void)restoreSessionCerts;
2699
2700
    return NULL;
2701
}
2702
2703
#endif /* NO_SESSION_CACHE */
2704
2705
#if !defined(NO_TLS) && defined(WOLFSSL_TLS13) && \
2706
    defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
2707
#if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE)
2708
/* Does freeing a session's ex_data call anything? Only then can two cache
2709
 * entries holding the same ex_data free it twice. */
2710
static int SessionExDataHasFree(void)
2711
{
2712
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
2713
    return 1;
2714
#elif defined(HAVE_EX_DATA_CRYPTO)
2715
    const CRYPTO_EX_cb_ctx* cb;
2716
2717
    for (cb = crypto_ex_cb_ctx_session; cb != NULL; cb = cb->next) {
2718
        if (cb->free_func != NULL)
2719
            return 1;
2720
    }
2721
    return 0;
2722
#else
2723
    return 0;
2724
#endif
2725
}
2726
2727
/* Move ex_data ownership from the cache entry of ssl->session to the
2728
 * session. When the entry is gone or no longer owns it, another owner holds
2729
 * the ex_data, so drop the stale copy and own an empty one. */
2730
static void SessionTakeExData(WOLFSSL* ssl)
2731
{
2732
    WOLFSSL_SESSION* session = ssl->session;
2733
    WOLFSSL_SESSION* sess = NULL;
2734
    const byte* id;
2735
    word32 row = 0;
2736
    int taken = 0;
2737
2738
    if (session->ownExData || SslSessionCacheOff(ssl, session) ||
2739
            !SessionExDataHasFree()) {
2740
        return;
2741
    }
2742
#ifdef HAVE_EXT_CACHE
2743
    if (ssl->options.internalCacheOff)
2744
        return;
2745
#endif
2746
2747
    id = session->sessionID;
2748
    if (session->haveAltSessionID)
2749
        id = session->altSessionID;
2750
2751
    if (TlsSessionCacheGetAndWrLock(id, &sess, &row, ssl->options.side) == 0 &&
2752
            sess != NULL) {
2753
        if (sess->ownExData) {
2754
            XMEMCPY(&session->ex_data, &sess->ex_data,
2755
                    sizeof(WOLFSSL_CRYPTO_EX_DATA));
2756
            XMEMSET(&sess->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA));
2757
            sess->ownExData = 0;
2758
            taken = 1;
2759
        }
2760
        TlsSessionCacheUnlockRow(row);
2761
    }
2762
    if (!taken)
2763
        XMEMSET(&session->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA));
2764
    session->ownExData = 1;
2765
}
2766
#endif /* HAVE_EX_DATA && !NO_SESSION_CACHE */
2767
2768
/* Give ssl->session a new random ID to cache it under. The entry for the old
2769
 * ID may own the ex_data the session holds a copy of. Move it to the session
2770
 * first so the entry added for the new ID is the only owner. */
2771
int SessionNewAltId(WOLFSSL* ssl)
2772
{
2773
    byte id[ID_LEN];
2774
    int ret;
2775
2776
    ret = wc_RNG_GenerateBlock(ssl->rng, id, ID_LEN);
2777
    if (ret != 0)
2778
        return ret;
2779
#if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE)
2780
    SessionTakeExData(ssl);
2781
#endif
2782
    XMEMCPY(ssl->session->altSessionID, id, ID_LEN);
2783
    ssl->session->haveAltSessionID = 1;
2784
    return 0;
2785
}
2786
#endif /* !NO_TLS && WOLFSSL_TLS13 && HAVE_SESSION_TICKET &&
2787
        * !NO_WOLFSSL_SERVER */
2788
2789
#ifdef OPENSSL_EXTRA
2790
2791
   /* returns previous set cache size which stays constant */
2792
    long wolfSSL_CTX_sess_set_cache_size(WOLFSSL_CTX* ctx, long sz)
2793
    {
2794
        /* cache size fixed at compile time in wolfSSL */
2795
        (void)ctx;
2796
        (void)sz;
2797
        WOLFSSL_MSG("session cache is set at compile time");
2798
        #ifndef NO_SESSION_CACHE
2799
            return (long)(SESSIONS_PER_ROW * SESSION_ROWS);
2800
        #else
2801
            return 0;
2802
        #endif
2803
    }
2804
2805
2806
    long wolfSSL_CTX_sess_get_cache_size(WOLFSSL_CTX* ctx)
2807
    {
2808
        (void)ctx;
2809
        #ifndef NO_SESSION_CACHE
2810
            return (long)(SESSIONS_PER_ROW * SESSION_ROWS);
2811
        #else
2812
            return 0;
2813
        #endif
2814
    }
2815
2816
#endif
2817
2818
#ifndef NO_SESSION_CACHE
2819
int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session)
2820
0
{
2821
0
    int    error = 0;
2822
0
    const byte* id = NULL;
2823
0
    byte idSz = 0;
2824
2825
0
    WOLFSSL_ENTER("wolfSSL_CTX_add_session");
2826
2827
0
    session = ClientSessionToSession(session);
2828
0
    if (session == NULL)
2829
0
        return WOLFSSL_FAILURE;
2830
2831
    /* Session cache is global */
2832
0
    (void)ctx;
2833
2834
0
    if (session->haveAltSessionID) {
2835
0
        id = session->altSessionID;
2836
0
        idSz = ID_LEN;
2837
0
    }
2838
0
    else {
2839
0
        id = session->sessionID;
2840
0
        idSz = session->sessionIDSz;
2841
0
    }
2842
2843
0
    error = AddSessionToCache(ctx, session, id, idSz,
2844
0
            NULL, session->side,
2845
#ifdef HAVE_SESSION_TICKET
2846
            session->ticketLen > 0,
2847
#else
2848
0
            0,
2849
0
#endif
2850
0
            NULL);
2851
2852
0
    return error == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
2853
0
}
2854
#endif
2855
2856
#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \
2857
        defined(HAVE_EXT_CACHE))
2858
/* stunnel 4.28 needs
2859
 *
2860
 * Callback that is called if a session tries to resume but could not find
2861
 * the session to resume it.
2862
 */
2863
void wolfSSL_CTX_sess_set_get_cb(WOLFSSL_CTX* ctx,
2864
    WOLFSSL_SESSION*(*f)(WOLFSSL*, const unsigned char*, int, int*))
2865
{
2866
    if (ctx == NULL)
2867
        return;
2868
2869
#ifdef HAVE_EXT_CACHE
2870
    ctx->get_sess_cb = f;
2871
#else
2872
    (void)f;
2873
#endif
2874
}
2875
2876
void wolfSSL_CTX_sess_set_new_cb(WOLFSSL_CTX* ctx,
2877
                             int (*f)(WOLFSSL*, WOLFSSL_SESSION*))
2878
{
2879
    if (ctx == NULL)
2880
        return;
2881
2882
#ifdef HAVE_EXT_CACHE
2883
    ctx->new_sess_cb = f;
2884
#else
2885
    (void)f;
2886
#endif
2887
}
2888
2889
void wolfSSL_CTX_sess_set_remove_cb(WOLFSSL_CTX* ctx, void (*f)(WOLFSSL_CTX*,
2890
                                                        WOLFSSL_SESSION*))
2891
{
2892
    if (ctx == NULL)
2893
        return;
2894
2895
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
2896
    ctx->rem_sess_cb = f;
2897
#else
2898
    (void)f;
2899
#endif
2900
}
2901
2902
2903
/*
2904
 *
2905
 * Note: It is expected that the importing and exporting function have been
2906
 *       built with the same settings. For example if session tickets was
2907
 *       enabled with the wolfSSL library exporting a session then it is
2908
 *       expected to be turned on with the wolfSSL library importing the
2909
 *       session.
2910
 */
2911
int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p)
2912
{
2913
    int size = 0;
2914
#ifdef HAVE_EXT_CACHE
2915
    int idx = 0;
2916
#ifdef SESSION_CERTS
2917
    int i;
2918
#endif
2919
2920
    WOLFSSL_ENTER("wolfSSL_i2d_SSL_SESSION");
2921
2922
    sess = ClientSessionToSession(sess);
2923
    if (sess == NULL) {
2924
        return BAD_FUNC_ARG;
2925
    }
2926
2927
    /* side | bornOn | timeout | sessionID len | sessionID | masterSecret |
2928
     * haveEMS  */
2929
    size += OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN +
2930
            sess->sessionIDSz + SECRET_LEN + OPAQUE8_LEN;
2931
    /* altSessionID */
2932
    size += OPAQUE8_LEN + (sess->haveAltSessionID ? ID_LEN : 0);
2933
#ifdef SESSION_CERTS
2934
    /* Peer chain */
2935
    size += OPAQUE8_LEN;
2936
    for (i = 0; i < sess->chain.count; i++)
2937
        size += OPAQUE16_LEN + sess->chain.certs[i].length;
2938
#endif
2939
    /* Protocol version */
2940
    size += OPAQUE16_LEN;
2941
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
2942
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
2943
    /* cipher suite */
2944
    size += OPAQUE16_LEN;
2945
#endif
2946
#ifndef NO_CLIENT_CACHE
2947
    /* ServerID len | ServerID */
2948
    size += OPAQUE16_LEN + sess->idLen;
2949
#endif
2950
#ifdef WOLFSSL_SESSION_ID_CTX
2951
    /* session context ID len | session context ID */
2952
    size += OPAQUE8_LEN + sess->sessionCtxSz;
2953
#endif
2954
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
2955
    /* peerVerifyRet */
2956
    size += OPAQUE8_LEN;
2957
#endif
2958
#ifdef WOLFSSL_TLS13
2959
    /* namedGroup */
2960
    size += OPAQUE16_LEN;
2961
#endif
2962
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2963
#ifdef WOLFSSL_TLS13
2964
#ifdef WOLFSSL_32BIT_MILLI_TIME
2965
    /* ticketSeen | ticketAdd */
2966
    size += OPAQUE32_LEN + OPAQUE32_LEN;
2967
#else
2968
    /* ticketSeen Hi 32 bits | ticketSeen Lo 32 bits | ticketAdd */
2969
    size += OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE32_LEN;
2970
#endif /* WOLFSSL_32BIT_MILLI_TIME */
2971
    /* ticketNonce */
2972
    size += OPAQUE8_LEN + sess->ticketNonce.len;
2973
#endif /* WOLFSSL_TLS13 */
2974
#ifdef WOLFSSL_EARLY_DATA
2975
    size += OPAQUE32_LEN;
2976
#endif /* WOLFSSL_EARLY_DATA */
2977
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
2978
#ifdef HAVE_SESSION_TICKET
2979
    /* ticket len | ticket */
2980
    size += OPAQUE16_LEN + sess->ticketLen;
2981
#endif /* HAVE_SESSION_TICKET */
2982
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
2983
#ifdef HAVE_SNI
2984
    /* sniHash */
2985
    size += TICKET_BINDING_HASH_SZ;
2986
#endif /* HAVE_SNI */
2987
#ifdef HAVE_ALPN
2988
    /* alpnHash */
2989
    size += TICKET_BINDING_HASH_SZ;
2990
#endif /* HAVE_ALPN */
2991
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
2992
#ifndef NO_WOLFSSL_SERVER
2993
    /* peerAuthOk and isPSK */
2994
    size += OPAQUE8_LEN;
2995
#endif
2996
2997
    if (p != NULL) {
2998
        unsigned char *data;
2999
3000
        if (*p == NULL)
3001
            *p = (unsigned char*)XMALLOC((size_t)size, NULL,
3002
                                                DYNAMIC_TYPE_OPENSSL);
3003
        if (*p == NULL)
3004
            return 0;
3005
        data = *p;
3006
3007
        data[idx++] = sess->side;
3008
        c32toa(sess->bornOn, data + idx); idx += OPAQUE32_LEN;
3009
        c32toa(sess->timeout, data + idx); idx += OPAQUE32_LEN;
3010
        data[idx++] = sess->sessionIDSz;
3011
        XMEMCPY(data + idx, sess->sessionID, sess->sessionIDSz);
3012
        idx += sess->sessionIDSz;
3013
        XMEMCPY(data + idx, sess->masterSecret, SECRET_LEN); idx += SECRET_LEN;
3014
        data[idx++] = (byte)sess->haveEMS;
3015
        data[idx++] = sess->haveAltSessionID ? ID_LEN : 0;
3016
        if (sess->haveAltSessionID) {
3017
            XMEMCPY(data + idx, sess->altSessionID, ID_LEN);
3018
            idx += ID_LEN;
3019
        }
3020
#ifdef SESSION_CERTS
3021
        data[idx++] = (byte)sess->chain.count;
3022
        for (i = 0; i < sess->chain.count; i++) {
3023
            c16toa((word16)sess->chain.certs[i].length, data + idx);
3024
            idx += OPAQUE16_LEN;
3025
            XMEMCPY(data + idx, sess->chain.certs[i].buffer,
3026
                    (size_t)sess->chain.certs[i].length);
3027
            idx += sess->chain.certs[i].length;
3028
        }
3029
#endif
3030
        data[idx++] = sess->version.major;
3031
        data[idx++] = sess->version.minor;
3032
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
3033
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
3034
        data[idx++] = sess->cipherSuite0;
3035
        data[idx++] = sess->cipherSuite;
3036
#endif
3037
#ifndef NO_CLIENT_CACHE
3038
        c16toa(sess->idLen, data + idx); idx += OPAQUE16_LEN;
3039
        XMEMCPY(data + idx, sess->serverID, sess->idLen);
3040
        idx += sess->idLen;
3041
#endif
3042
#ifdef WOLFSSL_SESSION_ID_CTX
3043
        data[idx++] = sess->sessionCtxSz;
3044
        XMEMCPY(data + idx, sess->sessionCtx, sess->sessionCtxSz);
3045
        idx += sess->sessionCtxSz;
3046
#endif
3047
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
3048
        data[idx++] = sess->peerVerifyRet;
3049
#endif
3050
#ifdef WOLFSSL_TLS13
3051
        c16toa(sess->namedGroup, data + idx);
3052
        idx += OPAQUE16_LEN;
3053
#endif
3054
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3055
#ifdef WOLFSSL_TLS13
3056
#ifdef WOLFSSL_32BIT_MILLI_TIME
3057
        c32toa(sess->ticketSeen, data + idx);
3058
        idx += OPAQUE32_LEN;
3059
#else
3060
        c32toa((word32)(sess->ticketSeen >> 32), data + idx);
3061
        idx += OPAQUE32_LEN;
3062
        c32toa((word32)sess->ticketSeen, data + idx);
3063
        idx += OPAQUE32_LEN;
3064
#endif /* WOLFSSL_32BIT_MILLI_TIME */
3065
        c32toa(sess->ticketAdd, data + idx);
3066
        idx += OPAQUE32_LEN;
3067
        data[idx++] = sess->ticketNonce.len;
3068
        XMEMCPY(data + idx, sess->ticketNonce.data, sess->ticketNonce.len);
3069
        idx += sess->ticketNonce.len;
3070
#endif /* WOLFSSL_TLS13 */
3071
#ifdef WOLFSSL_EARLY_DATA
3072
        c32toa(sess->maxEarlyDataSz, data + idx);
3073
        idx += OPAQUE32_LEN;
3074
#endif /* WOLFSSL_EARLY_DATA */
3075
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
3076
#ifdef HAVE_SESSION_TICKET
3077
        c16toa(sess->ticketLen, data + idx); idx += OPAQUE16_LEN;
3078
        XMEMCPY(data + idx, sess->ticket, sess->ticketLen);
3079
        idx += sess->ticketLen;
3080
#endif /* HAVE_SESSION_TICKET */
3081
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
3082
#ifdef HAVE_SNI
3083
        XMEMCPY(data + idx, sess->sniHash, TICKET_BINDING_HASH_SZ);
3084
        idx += TICKET_BINDING_HASH_SZ;
3085
#endif /* HAVE_SNI */
3086
#ifdef HAVE_ALPN
3087
        XMEMCPY(data + idx, sess->alpnHash, TICKET_BINDING_HASH_SZ);
3088
        idx += TICKET_BINDING_HASH_SZ;
3089
#endif /* HAVE_ALPN */
3090
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
3091
#ifndef NO_WOLFSSL_SERVER
3092
        data[idx++] = (byte)(sess->peerAuthOk | (sess->isPSK << 1));
3093
#endif
3094
    }
3095
#endif /* HAVE_EXT_CACHE */
3096
3097
    (void)sess;
3098
    (void)p;
3099
#ifdef HAVE_EXT_CACHE
3100
    (void)idx;
3101
#endif
3102
3103
    return size;
3104
}
3105
3106
3107
/* TODO: no function to free new session.
3108
 *
3109
 * Note: It is expected that the importing and exporting function have been
3110
 *       built with the same settings. For example if session tickets was
3111
 *       enabled with the wolfSSL library exporting a session then it is
3112
 *       expected to be turned on with the wolfSSL library importing the
3113
 *       session.
3114
 *
3115
 * i is how many bytes are readable at *p, not necessarily the size of the
3116
 * session: trailing bytes are ignored, and *p is advanced to the end of the
3117
 * session decoded, so sessions stored back to back decode with repeated
3118
 * calls. Passing in too few bytes will cause an error.
3119
 */
3120
WOLFSSL_SESSION* wolfSSL_d2i_SSL_SESSION(WOLFSSL_SESSION** sess,
3121
                                const unsigned char** p, long i)
3122
{
3123
    WOLFSSL_SESSION* s = NULL;
3124
    int ret = 0;
3125
#if defined(HAVE_EXT_CACHE)
3126
    int idx = 0;
3127
    byte* data;
3128
#ifdef SESSION_CERTS
3129
    int j;
3130
    word16 length;
3131
#endif
3132
#endif /* HAVE_EXT_CACHE */
3133
3134
    (void)p;
3135
    (void)i;
3136
    (void)ret;
3137
    (void)sess;
3138
3139
#ifdef HAVE_EXT_CACHE
3140
    if (p == NULL || *p == NULL)
3141
        return NULL;
3142
3143
    s = wolfSSL_SESSION_new();
3144
    if (s == NULL)
3145
        return NULL;
3146
3147
    idx = 0;
3148
    data = (byte*)*p;
3149
3150
    /* side | bornOn | timeout | sessionID len */
3151
    if (i < OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN) {
3152
        ret = BUFFER_ERROR;
3153
        goto end;
3154
    }
3155
    s->side = data[idx++];
3156
    ato32(data + idx, &s->bornOn); idx += OPAQUE32_LEN;
3157
    ato32(data + idx, &s->timeout); idx += OPAQUE32_LEN;
3158
    s->sessionIDSz = data[idx++];
3159
    if (s->sessionIDSz > ID_LEN) {
3160
        ret = BUFFER_ERROR;
3161
        goto end;
3162
    }
3163
3164
    /* sessionID | secret | haveEMS | haveAltSessionID */
3165
    if (i - idx < s->sessionIDSz + SECRET_LEN + OPAQUE8_LEN + OPAQUE8_LEN) {
3166
        ret = BUFFER_ERROR;
3167
        goto end;
3168
    }
3169
    XMEMCPY(s->sessionID, data + idx, s->sessionIDSz);
3170
    idx  += s->sessionIDSz;
3171
    XMEMCPY(s->masterSecret, data + idx, SECRET_LEN); idx += SECRET_LEN;
3172
    s->haveEMS = data[idx++];
3173
    if (data[idx] != ID_LEN && data[idx] != 0) {
3174
        ret = BUFFER_ERROR;
3175
        goto end;
3176
    }
3177
    s->haveAltSessionID = data[idx++] == ID_LEN;
3178
3179
    /* altSessionID */
3180
    if (s->haveAltSessionID) {
3181
        if (i - idx < ID_LEN) {
3182
            ret = BUFFER_ERROR;
3183
            goto end;
3184
        }
3185
        XMEMCPY(s->altSessionID, data + idx, ID_LEN); idx += ID_LEN;
3186
    }
3187
3188
#ifdef SESSION_CERTS
3189
    /* Certificate chain */
3190
    if (i - idx == 0) {
3191
        ret = BUFFER_ERROR;
3192
        goto end;
3193
    }
3194
    s->chain.count = data[idx++];
3195
    if (s->chain.count > MAX_CHAIN_DEPTH) {
3196
        ret = BUFFER_ERROR;
3197
        goto end;
3198
    }
3199
    for (j = 0; j < s->chain.count; j++) {
3200
        if (i - idx < OPAQUE16_LEN) {
3201
            ret = BUFFER_ERROR;
3202
            goto end;
3203
        }
3204
        ato16(data + idx, &length); idx += OPAQUE16_LEN;
3205
        if (length > MAX_X509_SIZE) {
3206
            ret = BUFFER_ERROR;
3207
            goto end;
3208
        }
3209
        s->chain.certs[j].length = length;
3210
        if (i - idx < length) {
3211
            ret = BUFFER_ERROR;
3212
            goto end;
3213
        }
3214
        XMEMCPY(s->chain.certs[j].buffer, data + idx, length);
3215
        idx += length;
3216
    }
3217
#endif
3218
    /* Protocol Version */
3219
    if (i - idx < OPAQUE16_LEN) {
3220
        ret = BUFFER_ERROR;
3221
        goto end;
3222
    }
3223
    s->version.major = data[idx++];
3224
    s->version.minor = data[idx++];
3225
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
3226
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
3227
    /* Cipher suite */
3228
    if (i - idx < OPAQUE16_LEN) {
3229
        ret = BUFFER_ERROR;
3230
        goto end;
3231
    }
3232
    s->cipherSuite0 = data[idx++];
3233
    s->cipherSuite = data[idx++];
3234
#endif
3235
#ifndef NO_CLIENT_CACHE
3236
    /* ServerID len */
3237
    if (i - idx < OPAQUE16_LEN) {
3238
        ret = BUFFER_ERROR;
3239
        goto end;
3240
    }
3241
    ato16(data + idx, &s->idLen); idx += OPAQUE16_LEN;
3242
    if (s->idLen > SERVER_ID_LEN) {
3243
        ret = BUFFER_ERROR;
3244
        goto end;
3245
    }
3246
3247
    /* ServerID */
3248
    if (i - idx < s->idLen) {
3249
        ret = BUFFER_ERROR;
3250
        goto end;
3251
    }
3252
    XMEMCPY(s->serverID, data + idx, s->idLen); idx += s->idLen;
3253
#endif
3254
#ifdef WOLFSSL_SESSION_ID_CTX
3255
    /* byte for length of session context ID */
3256
    if (i - idx < OPAQUE8_LEN) {
3257
        ret = BUFFER_ERROR;
3258
        goto end;
3259
    }
3260
    s->sessionCtxSz = data[idx++];
3261
    if (s->sessionCtxSz > ID_LEN) {
3262
        ret = BUFFER_ERROR;
3263
        goto end;
3264
    }
3265
3266
    /* app session context ID */
3267
    if (i - idx < s->sessionCtxSz) {
3268
        ret = BUFFER_ERROR;
3269
        goto end;
3270
    }
3271
    XMEMCPY(s->sessionCtx, data + idx, s->sessionCtxSz); idx += s->sessionCtxSz;
3272
#endif
3273
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
3274
    /* byte for peerVerifyRet */
3275
    if (i - idx < OPAQUE8_LEN) {
3276
        ret = BUFFER_ERROR;
3277
        goto end;
3278
    }
3279
    s->peerVerifyRet = data[idx++];
3280
#endif
3281
#ifdef WOLFSSL_TLS13
3282
    if (i - idx < OPAQUE16_LEN) {
3283
        ret = BUFFER_ERROR;
3284
        goto end;
3285
    }
3286
    ato16(data + idx, &s->namedGroup);
3287
    idx += OPAQUE16_LEN;
3288
#endif
3289
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3290
#ifdef WOLFSSL_TLS13
3291
3292
#ifdef WOLFSSL_32BIT_MILLI_TIME
3293
    if (i - idx < OPAQUE32_LEN) {
3294
        ret = BUFFER_ERROR;
3295
        goto end;
3296
    }
3297
    ato32(data + idx, &s->ticketSeen);
3298
    idx += OPAQUE32_LEN;
3299
#else
3300
    if (i - idx < (OPAQUE32_LEN * 2)) {
3301
        ret = BUFFER_ERROR;
3302
        goto end;
3303
    }
3304
    {
3305
        word32 seenHi, seenLo;
3306
        ato32(data + idx, &seenHi);
3307
        idx += OPAQUE32_LEN;
3308
        ato32(data + idx, &seenLo);
3309
        idx += OPAQUE32_LEN;
3310
        s->ticketSeen = ((sword64)seenHi << 32) + seenLo;
3311
    }
3312
#endif /* WOLFSSL_32BIT_MILLI_TIME */
3313
3314
    if (i - idx < OPAQUE32_LEN) {
3315
        ret = BUFFER_ERROR;
3316
        goto end;
3317
    }
3318
    ato32(data + idx, &s->ticketAdd);
3319
    idx += OPAQUE32_LEN;
3320
    if (i - idx < OPAQUE8_LEN) {
3321
        ret = BUFFER_ERROR;
3322
        goto end;
3323
    }
3324
    s->ticketNonce.len = data[idx++];
3325
3326
    if (i - idx < s->ticketNonce.len) {
3327
        ret = BUFFER_ERROR;
3328
        goto end;
3329
    }
3330
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                     \
3331
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
3332
    ret = SessionTicketNoncePopulate(s, data + idx, s->ticketNonce.len);
3333
    if (ret != 0)
3334
        goto end;
3335
#else
3336
    if (s->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ) {
3337
        ret = BUFFER_ERROR;
3338
        goto end;
3339
    }
3340
    XMEMCPY(s->ticketNonce.data, data + idx, s->ticketNonce.len);
3341
#endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */
3342
3343
    idx += s->ticketNonce.len;
3344
#endif /* WOLFSSL_TLS13 */
3345
#ifdef WOLFSSL_EARLY_DATA
3346
    if (i - idx < OPAQUE32_LEN) {
3347
        ret = BUFFER_ERROR;
3348
        goto end;
3349
    }
3350
    ato32(data + idx, &s->maxEarlyDataSz);
3351
    idx += OPAQUE32_LEN;
3352
#endif /* WOLFSSL_EARLY_DATA */
3353
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
3354
#ifdef HAVE_SESSION_TICKET
3355
    /* ticket len */
3356
    if (i - idx < OPAQUE16_LEN) {
3357
        ret = BUFFER_ERROR;
3358
        goto end;
3359
    }
3360
    ato16(data + idx, &s->ticketLen); idx += OPAQUE16_LEN;
3361
3362
    /* Dispose of ol dynamic ticket and ensure space for new ticket. */
3363
    if (s->ticketLenAlloc > 0) {
3364
        XFREE(s->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK);
3365
    }
3366
    if (s->ticketLen <= SESSION_TICKET_LEN)
3367
        s->ticket = s->staticTicket;
3368
    else {
3369
        s->ticket = (byte*)XMALLOC(s->ticketLen, NULL,
3370
                                   DYNAMIC_TYPE_SESSION_TICK);
3371
        if (s->ticket == NULL) {
3372
            ret = MEMORY_ERROR;
3373
            goto end;
3374
        }
3375
        s->ticketLenAlloc = (word16)s->ticketLen;
3376
    }
3377
3378
    /* ticket */
3379
    if (i - idx < s->ticketLen) {
3380
        ret = BUFFER_ERROR;
3381
        goto end;
3382
    }
3383
    XMEMCPY(s->ticket, data + idx, s->ticketLen); idx += s->ticketLen;
3384
#endif /* HAVE_SESSION_TICKET */
3385
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
3386
#ifdef HAVE_SNI
3387
    /* sniHash - SNI binding for stateful resumption (RFC 6066 section 3) */
3388
    if (i - idx < TICKET_BINDING_HASH_SZ) {
3389
        ret = BUFFER_ERROR;
3390
        goto end;
3391
    }
3392
    XMEMCPY(s->sniHash, data + idx, TICKET_BINDING_HASH_SZ);
3393
    idx += TICKET_BINDING_HASH_SZ;
3394
#endif /* HAVE_SNI */
3395
#ifdef HAVE_ALPN
3396
    /* alpnHash - ALPN binding for stateful resumption */
3397
    if (i - idx < TICKET_BINDING_HASH_SZ) {
3398
        ret = BUFFER_ERROR;
3399
        goto end;
3400
    }
3401
    XMEMCPY(s->alpnHash, data + idx, TICKET_BINDING_HASH_SZ);
3402
    idx += TICKET_BINDING_HASH_SZ;
3403
#endif /* HAVE_ALPN */
3404
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
3405
#ifndef NO_WOLFSSL_SERVER
3406
    if (i - idx < OPAQUE8_LEN) {
3407
        ret = BUFFER_ERROR;
3408
        goto end;
3409
    }
3410
    s->peerAuthOk = (data[idx] & 0x01) != 0;
3411
    s->isPSK = (data[idx] & 0x02) != 0;
3412
    idx++;
3413
#endif
3414
3415
    if (sess != NULL) {
3416
        wolfSSL_FreeSession(NULL, *sess);
3417
        *sess = s;
3418
    }
3419
3420
    s->isSetup = 1;
3421
3422
    *p += idx;
3423
3424
end:
3425
    if (ret != 0 && (sess == NULL || *sess != s)) {
3426
        wolfSSL_FreeSession(NULL, s);
3427
        s = NULL;
3428
    }
3429
#endif /* HAVE_EXT_CACHE */
3430
    return s;
3431
}
3432
3433
/* Check if there is a session ticket associated with this WOLFSSL_SESSION.
3434
 *
3435
 * sess - pointer to WOLFSSL_SESSION struct
3436
 *
3437
 * Returns 1 if has session ticket, otherwise 0 */
3438
int wolfSSL_SESSION_has_ticket(const WOLFSSL_SESSION* sess)
3439
{
3440
    WOLFSSL_ENTER("wolfSSL_SESSION_has_ticket");
3441
#ifdef HAVE_SESSION_TICKET
3442
    sess = ClientSessionToSession(sess);
3443
    if (sess) {
3444
        if ((sess->ticketLen > 0) && (sess->ticket != NULL)) {
3445
            return WOLFSSL_SUCCESS;
3446
        }
3447
    }
3448
#else
3449
    (void)sess;
3450
#endif
3451
    return WOLFSSL_FAILURE;
3452
}
3453
3454
unsigned long wolfSSL_SESSION_get_ticket_lifetime_hint(
3455
                  const WOLFSSL_SESSION* sess)
3456
{
3457
    WOLFSSL_ENTER("wolfSSL_SESSION_get_ticket_lifetime_hint");
3458
    sess = ClientSessionToSession(sess);
3459
    if (sess) {
3460
        return sess->timeout;
3461
    }
3462
    return 0;
3463
}
3464
3465
long wolfSSL_SESSION_get_timeout(const WOLFSSL_SESSION* sess)
3466
{
3467
    long timeout = 0;
3468
    WOLFSSL_ENTER("wolfSSL_SESSION_get_timeout");
3469
    sess = ClientSessionToSession(sess);
3470
    if (sess)
3471
        timeout = sess->timeout;
3472
    return timeout;
3473
}
3474
3475
long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t)
3476
{
3477
    word32 tmptime;
3478
3479
    ses = ClientSessionToSession(ses);
3480
    if (ses == NULL || t < 0) {
3481
        return BAD_FUNC_ARG;
3482
    }
3483
3484
    tmptime = t & 0xFFFFFFFF;
3485
    ses->timeout = tmptime;
3486
3487
    return WOLFSSL_SUCCESS;
3488
}
3489
3490
long wolfSSL_SESSION_get_time(const WOLFSSL_SESSION* sess)
3491
{
3492
    long bornOn = 0;
3493
    WOLFSSL_ENTER("wolfSSL_SESSION_get_time");
3494
    sess = ClientSessionToSession(sess);
3495
    if (sess)
3496
        bornOn = sess->bornOn;
3497
    return bornOn;
3498
}
3499
3500
long wolfSSL_SESSION_set_time(WOLFSSL_SESSION *ses, long t)
3501
{
3502
3503
    ses = ClientSessionToSession(ses);
3504
    if (ses == NULL || t < 0) {
3505
        return 0;
3506
    }
3507
    ses->bornOn = (word32)t;
3508
    return t;
3509
}
3510
3511
#endif /* !NO_SESSION_CACHE && (OPENSSL_EXTRA || HAVE_EXT_CACHE) */
3512
3513
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
3514
    defined(HAVE_EX_DATA)
3515
3516
#if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE)
3517
static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx,
3518
        void* data, byte get, void** getRet, int* setRet)
3519
{
3520
    int row;
3521
    int i;
3522
    int error = 0;
3523
    SessionRow* sessRow = NULL;
3524
    const byte* id;
3525
    byte foundCache = 0;
3526
3527
    if (getRet != NULL)
3528
        *getRet = NULL;
3529
    if (setRet != NULL)
3530
        *setRet = WOLFSSL_FAILURE;
3531
3532
    id = session->sessionID;
3533
    if (session->haveAltSessionID)
3534
        id = session->altSessionID;
3535
    else if (session->sessionIDSz != ID_LEN) {
3536
        WOLFSSL_MSG("Incorrect sessionIDSz");
3537
        return;
3538
    }
3539
3540
    row = (int)SessionCacheRow(id, session->side, &error);
3541
    if (error != 0) {
3542
        WOLFSSL_MSG("Hash session failed");
3543
        return;
3544
    }
3545
3546
    sessRow = &SessionCache[row];
3547
    if (get)
3548
        error = SESSION_ROW_RD_LOCK(sessRow);
3549
    else
3550
        error = SESSION_ROW_WR_LOCK(sessRow);
3551
    if (error != 0) {
3552
        WOLFSSL_MSG("Session row lock failed");
3553
        return;
3554
    }
3555
3556
    for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) {
3557
        WOLFSSL_SESSION* cacheSession;
3558
#ifdef SESSION_CACHE_DYNAMIC_MEM
3559
        cacheSession = sessRow->Sessions[i];
3560
#else
3561
        cacheSession = &sessRow->Sessions[i];
3562
#endif
3563
        if (cacheSession && cacheSession->sessionIDSz == ID_LEN &&
3564
                XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0
3565
                && session->side == cacheSession->side
3566
                && (IsAtLeastTLSv1_3(session->version) ==
3567
                    IsAtLeastTLSv1_3(cacheSession->version))
3568
                /* An entry that gave its ex_data to a reissued ticket no
3569
                 * longer holds this session's ex_data. */
3570
                && cacheSession->ownExData
3571
            ) {
3572
            if (get) {
3573
                if (getRet) {
3574
                    *getRet = wolfSSL_CRYPTO_get_ex_data(
3575
                        &cacheSession->ex_data, idx);
3576
                }
3577
            }
3578
            else {
3579
                if (setRet) {
3580
                    *setRet = wolfSSL_CRYPTO_set_ex_data(
3581
                        &cacheSession->ex_data, idx, data);
3582
                }
3583
            }
3584
            foundCache = 1;
3585
            break;
3586
        }
3587
    }
3588
    SESSION_ROW_UNLOCK(sessRow);
3589
    /* If we don't have a session in cache then clear the ex_data and
3590
     * own it */
3591
    if (!foundCache) {
3592
        XMEMSET(&session->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA));
3593
        session->ownExData = 1;
3594
        if (!get) {
3595
            *setRet = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx,
3596
                    data);
3597
        }
3598
    }
3599
3600
}
3601
#endif
3602
3603
#endif
3604
3605
#ifndef NO_SESSION_CACHE
3606
/* OpenSSL-compatible return: 1 if the session was found and removed from the
3607
 * internal cache, or if the external remove callback (rem_sess_cb) was
3608
 * invoked. 0 if neither applied (not present, or null arguments). */
3609
int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s)
3610
{
3611
    int found = 0;
3612
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
3613
    int rem_called = FALSE;
3614
#endif
3615
3616
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_remove_session");
3617
3618
    s = ClientSessionToSession(s);
3619
    if (ctx == NULL || s == NULL)
3620
        return 0;
3621
3622
#ifdef HAVE_EXT_CACHE
3623
    if (!ctx->internalCacheOff)
3624
#endif
3625
    {
3626
        const byte* id;
3627
        WOLFSSL_SESSION *sess = NULL;
3628
        word32 row = 0;
3629
        int ret;
3630
3631
        id = s->sessionID;
3632
        if (s->haveAltSessionID)
3633
            id = s->altSessionID;
3634
3635
        ret = TlsSessionCacheGetAndWrLock(id, &sess, &row, ctx->method->side);
3636
        if (ret == 0 && sess != NULL) {
3637
            found = 1;
3638
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
3639
            if (sess->rem_sess_cb != NULL) {
3640
                rem_called = TRUE;
3641
            }
3642
#endif
3643
            /* Call this before changing ownExData so that calls to ex_data
3644
             * don't try to access the SessionCache again. */
3645
            EvictSessionFromCache(sess);
3646
#ifdef HAVE_EX_DATA
3647
            if (sess->ownExData) {
3648
                /* Most recent version of ex data is in cache. Copy it
3649
                 * over so the user can free it. */
3650
                XMEMCPY(&s->ex_data, &sess->ex_data,
3651
                        sizeof(WOLFSSL_CRYPTO_EX_DATA));
3652
                s->ownExData = 1;
3653
                sess->ownExData = 0;
3654
            }
3655
#endif
3656
#ifdef SESSION_CACHE_DYNAMIC_MEM
3657
            {
3658
                /* Find and clear entry. Row is locked so we are good to go. */
3659
                int idx;
3660
                for (idx = 0; idx < SESSIONS_PER_ROW; idx++) {
3661
                    if (sess == SessionCache[row].Sessions[idx]) {
3662
                        XFREE(sess, sess->heap, DYNAMIC_TYPE_SESSION);
3663
                        SessionCache[row].Sessions[idx] = NULL;
3664
                        break;
3665
                    }
3666
                }
3667
            }
3668
#endif
3669
            TlsSessionCacheUnlockRow(row);
3670
        }
3671
    }
3672
3673
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
3674
    if (ctx->rem_sess_cb != NULL && !rem_called) {
3675
        ctx->rem_sess_cb(ctx, s);
3676
        /* Assume the external cache had the session. */
3677
        found = 1;
3678
    }
3679
#endif
3680
3681
    return found;
3682
}
3683
3684
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
3685
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
3686
WOLFSSL_SESSION *wolfSSL_SSL_get0_session(const WOLFSSL *ssl)
3687
{
3688
    WOLFSSL_ENTER("wolfSSL_SSL_get0_session");
3689
3690
    return ssl->session;
3691
}
3692
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
3693
    OPENSSL_EXTRA || HAVE_LIGHTY */
3694
3695
#endif /* NO_SESSION_CACHE */
3696
3697
#ifdef WOLFSSL_SESSION_EXPORT
3698
/* Used to import a serialized TLS session.
3699
 * WARNING: buf contains sensitive information about the state and is best to be
3700
 *          encrypted before storing if stored.
3701
 *
3702
 * @param ssl WOLFSSL structure to import the session into
3703
 * @param buf serialized session
3704
 * @param sz  size of buffer 'buf'
3705
 * @return the number of bytes read from buffer 'buf'
3706
 */
3707
int wolfSSL_tls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
3708
{
3709
    if (ssl == NULL || buf == NULL) {
3710
        return BAD_FUNC_ARG;
3711
    }
3712
    return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
3713
}
3714
3715
3716
/* Used to export a serialized TLS session.
3717
 * WARNING: buf contains sensitive information about the state and is best to be
3718
 *          encrypted before storing if stored.
3719
 *
3720
 * @param ssl WOLFSSL structure to export the session from
3721
 * @param buf output of serialized session
3722
 * @param sz  size in bytes set in 'buf'
3723
 * @return the number of bytes written into buffer 'buf'
3724
 */
3725
int wolfSSL_tls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
3726
{
3727
    if (ssl == NULL || sz == NULL) {
3728
        return BAD_FUNC_ARG;
3729
    }
3730
    return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS);
3731
}
3732
3733
#ifdef WOLFSSL_DTLS
3734
int wolfSSL_dtls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz)
3735
{
3736
    WOLFSSL_ENTER("wolfSSL_session_import");
3737
3738
    if (ssl == NULL || buf == NULL) {
3739
        return BAD_FUNC_ARG;
3740
    }
3741
3742
    /* sanity checks on buffer and protocol are done in internal function */
3743
    return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
3744
}
3745
3746
3747
/* Sets the function to call for serializing the session. This function is
3748
 * called right after the handshake is completed. */
3749
int wolfSSL_CTX_dtls_set_export(WOLFSSL_CTX* ctx, wc_dtls_export func)
3750
{
3751
3752
    WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_export");
3753
3754
    /* purposefully allow func to be NULL */
3755
    if (ctx == NULL) {
3756
        return BAD_FUNC_ARG;
3757
    }
3758
3759
    ctx->dtls_export = func;
3760
3761
    return WOLFSSL_SUCCESS;
3762
}
3763
3764
/* Sets the function in WOLFSSL struct to call for serializing the session. This
3765
 * function is called right after the handshake is completed. */
3766
int wolfSSL_dtls_set_export(WOLFSSL* ssl, wc_dtls_export func)
3767
{
3768
3769
    WOLFSSL_ENTER("wolfSSL_dtls_set_export");
3770
3771
    /* purposefully allow func to be NULL */
3772
    if (ssl == NULL) {
3773
        return BAD_FUNC_ARG;
3774
    }
3775
3776
    ssl->dtls_export = func;
3777
3778
    return WOLFSSL_SUCCESS;
3779
}
3780
3781
3782
/* This function allows for directly serializing a session rather than using
3783
 * callbacks. It has less overhead by removing a temporary buffer and gives
3784
 * control over when the session gets serialized. When using callbacks the
3785
 * session is always serialized immediately after the handshake is finished.
3786
 *
3787
 * buf is the argument to contain the serialized session
3788
 * sz  is the size of the buffer passed in
3789
 * ssl is the WOLFSSL struct to serialize
3790
 * returns the size of serialized session on success, 0 on no action, and
3791
 *         negative value on error */
3792
int wolfSSL_dtls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz)
3793
{
3794
    WOLFSSL_ENTER("wolfSSL_dtls_export");
3795
3796
    if (ssl == NULL || sz == NULL) {
3797
        return BAD_FUNC_ARG;
3798
    }
3799
3800
    if (buf == NULL) {
3801
        *sz = MAX_EXPORT_BUFFER;
3802
        return 0;
3803
    }
3804
3805
    /* if not DTLS do nothing */
3806
    if (!ssl->options.dtls) {
3807
        WOLFSSL_MSG("Currently only DTLS export is supported");
3808
        return 0;
3809
    }
3810
3811
    /* copy over keys, options, and dtls state struct */
3812
    return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS);
3813
}
3814
3815
3816
/* This function is similar to wolfSSL_dtls_export but only exports the portion
3817
 * of the WOLFSSL structure related to the state of the connection, i.e. peer
3818
 * sequence number, epoch, AEAD state etc.
3819
 *
3820
 * buf is the argument to contain the serialized state, if null then set "sz" to
3821
 *     buffer size required
3822
 * sz  is the size of the buffer passed in
3823
 * ssl is the WOLFSSL struct to serialize
3824
 * returns the size of serialized session on success, 0 on no action, and
3825
 *         negative value on error */
3826
int wolfSSL_dtls_export_state_only(WOLFSSL* ssl, unsigned char* buf,
3827
        unsigned int* sz)
3828
{
3829
    WOLFSSL_ENTER("wolfSSL_dtls_export_state_only");
3830
3831
    if (ssl == NULL || sz == NULL) {
3832
        return BAD_FUNC_ARG;
3833
    }
3834
3835
    if (buf == NULL) {
3836
        *sz = MAX_EXPORT_STATE_BUFFER;
3837
        return 0;
3838
    }
3839
3840
    /* if not DTLS do nothing */
3841
    if (!ssl->options.dtls) {
3842
        WOLFSSL_MSG("Currently only DTLS export state is supported");
3843
        return 0;
3844
    }
3845
3846
    /* copy over keys, options, and dtls state struct */
3847
    return wolfSSL_dtls_export_state_internal(ssl, buf, *sz);
3848
}
3849
3850
3851
/* returns 0 on success */
3852
int wolfSSL_send_session(WOLFSSL* ssl)
3853
{
3854
    int ret;
3855
    byte* buf;
3856
    word32 bufSz = MAX_EXPORT_BUFFER;
3857
3858
    WOLFSSL_ENTER("wolfSSL_send_session");
3859
3860
    if (ssl == NULL) {
3861
        return BAD_FUNC_ARG;
3862
    }
3863
3864
    buf = (byte*)XMALLOC(bufSz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
3865
    if (buf == NULL) {
3866
        return MEMORY_E;
3867
    }
3868
3869
    /* if not DTLS do nothing */
3870
    if (!ssl->options.dtls) {
3871
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
3872
        WOLFSSL_MSG("Currently only DTLS export is supported");
3873
        return 0;
3874
    }
3875
3876
    /* copy over keys, options, and dtls state struct */
3877
    ret = wolfSSL_session_export_internal(ssl, buf, &bufSz,
3878
        WOLFSSL_EXPORT_DTLS);
3879
    if (ret < 0) {
3880
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
3881
        return ret;
3882
    }
3883
3884
    /* if no error ret has size of buffer */
3885
    ret = ssl->dtls_export(ssl, buf, ret, NULL);
3886
    if (ret != WOLFSSL_SUCCESS) {
3887
        ForceZero(buf, bufSz);
3888
        XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
3889
        return ret;
3890
    }
3891
3892
    ForceZero(buf, bufSz);
3893
    XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
3894
    return 0;
3895
}
3896
#endif /* WOLFSSL_DTLS */
3897
#endif /* WOLFSSL_SESSION_EXPORT */
3898
3899
#ifdef OPENSSL_EXTRA
3900
3901
/* Copies the master secret over to out buffer. If outSz is 0 returns the size
3902
 * of master secret.
3903
 *
3904
 * ses : a session from completed TLS/SSL handshake
3905
 * out : buffer to hold copy of master secret
3906
 * outSz : size of out buffer
3907
 * returns : number of bytes copied into out buffer on success
3908
 *           less then or equal to 0 is considered a failure case
3909
 */
3910
int wolfSSL_SESSION_get_master_key(const WOLFSSL_SESSION* ses,
3911
        unsigned char* out, int outSz)
3912
{
3913
    int size;
3914
3915
    ses = ClientSessionToSession(ses);
3916
3917
    if (outSz == 0) {
3918
        return SECRET_LEN;
3919
    }
3920
3921
    if (ses == NULL || out == NULL || outSz < 0) {
3922
        return 0;
3923
    }
3924
3925
    if (outSz > SECRET_LEN) {
3926
        size = SECRET_LEN;
3927
    }
3928
    else {
3929
        size = outSz;
3930
    }
3931
3932
    XMEMCPY(out, ses->masterSecret, (size_t)size);
3933
    return size;
3934
}
3935
3936
3937
int wolfSSL_SESSION_get_master_key_length(const WOLFSSL_SESSION* ses)
3938
{
3939
    (void)ses;
3940
    return SECRET_LEN;
3941
}
3942
3943
#ifdef WOLFSSL_EARLY_DATA
3944
unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSION *session)
3945
{
3946
#ifndef NO_SESSION_CACHE
3947
    SessionRow* sessRow = NULL;
3948
#endif
3949
    /* Every value of the return type is a valid limit, 0 for none and
3950
     * 0xffffffff for QUIC, so there is no error value to report here. */
3951
    unsigned int ret = 0;
3952
3953
#ifndef NO_SESSION_CACHE
3954
    session = ClientSessionToSessionRdLocked(session, &sessRow);
3955
    if (session != NULL) {
3956
        ret = session->maxEarlyDataSz;
3957
    }
3958
    if (sessRow != NULL) {
3959
        SESSION_ROW_UNLOCK(sessRow);
3960
    }
3961
#else
3962
    if (session != NULL) {
3963
        ret = session->maxEarlyDataSz;
3964
    }
3965
#endif
3966
3967
    return ret;
3968
}
3969
#endif /* WOLFSSL_EARLY_DATA */
3970
3971
#endif /* OPENSSL_EXTRA */
3972
3973
void SetupSession(WOLFSSL* ssl)
3974
0
{
3975
0
    WOLFSSL_SESSION* session = ssl->session;
3976
3977
0
    WOLFSSL_ENTER("SetupSession");
3978
3979
0
    if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) {
3980
        /* Make sure the session ID is available when the user calls any
3981
         * get_session API */
3982
0
        if (!session->haveAltSessionID) {
3983
0
            XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN);
3984
0
            session->sessionIDSz = ssl->arrays->sessionIDSz;
3985
0
        }
3986
0
        else {
3987
0
            XMEMCPY(session->sessionID, session->altSessionID, ID_LEN);
3988
0
            session->sessionIDSz = ID_LEN;
3989
0
        }
3990
0
    }
3991
0
    session->side = (byte)ssl->options.side;
3992
0
    if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL)
3993
0
        XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN);
3994
    /* RFC8446 Appendix D.
3995
     *   implementations which support both TLS 1.3 and earlier versions SHOULD
3996
     *   indicate the use of the Extended Master Secret extension in their APIs
3997
     *   whenever TLS 1.3 is used.
3998
     * Set haveEMS so that we send the extension in subsequent connections that
3999
     * offer downgrades. */
4000
0
    if (IsAtLeastTLSv1_3(ssl->version))
4001
0
        session->haveEMS = 1;
4002
0
    else
4003
0
        session->haveEMS = ssl->options.haveEMS;
4004
    /* Server only: on a client these flags describe the server certificate,
4005
     * a different statement that nothing reads. A full handshake records its
4006
     * own outcome; a resumed one keeps what it inherited unless post-handshake
4007
     * auth added a certificate. */
4008
0
#ifndef NO_WOLFSSL_SERVER
4009
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
4010
0
        if (!ssl->options.resuming) {
4011
0
            session->peerAuthOk = 0;
4012
0
            session->isPSK = (byte)ssl->options.usingPSK_cipher;
4013
0
        }
4014
0
        if (SSL_PEER_CERT_VERIFIED(ssl))
4015
0
            session->peerAuthOk = 1;
4016
0
    }
4017
0
    else {
4018
0
        session->peerAuthOk = 0;
4019
0
        session->isPSK = 0;
4020
0
    }
4021
0
#endif
4022
#ifdef WOLFSSL_SESSION_ID_CTX
4023
    /* If using compatibility layer then check for and copy over session context
4024
     * id. */
4025
    if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) {
4026
        XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz);
4027
        session->sessionCtxSz = ssl->sessionCtxSz;
4028
    }
4029
#endif
4030
0
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
4031
    /* Bind the current SNI/ALPN to the session to verify on later resumption */
4032
0
#ifdef HAVE_SNI
4033
0
    (void)TicketSniHash(ssl, session->sniHash);
4034
0
#endif /* HAVE_SNI */
4035
#ifdef HAVE_ALPN
4036
    (void)TicketAlpnHash(ssl, session->alpnHash);
4037
#endif /* HAVE_ALPN */
4038
0
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
4039
0
    session->timeout = ssl->timeout;
4040
0
#ifndef NO_ASN_TIME
4041
0
    session->bornOn  = LowResTimer();
4042
0
#endif
4043
0
    session->version = ssl->version;
4044
0
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
4045
0
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
4046
0
    session->cipherSuite0 = ssl->options.cipherSuite0;
4047
0
    session->cipherSuite = ssl->options.cipherSuite;
4048
0
#endif
4049
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
4050
    session->peerVerifyRet = (byte)ssl->peerVerifyRet;
4051
#endif
4052
0
    session->isSetup = 1;
4053
0
}
4054
4055
#ifdef WOLFSSL_SESSION_ID_CTX
4056
    /* Storing app session context id, this value is inherited by WOLFSSL
4057
     * objects created from WOLFSSL_CTX. Any session that is imported with a
4058
     * different session context id will be rejected.
4059
     *
4060
     * ctx         structure to set context in
4061
     * sid_ctx     value of context to set
4062
     * sid_ctx_len length of sid_ctx buffer
4063
     *
4064
     * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing
4065
     */
4066
    int wolfSSL_CTX_set_session_id_context(WOLFSSL_CTX* ctx,
4067
                                           const unsigned char* sid_ctx,
4068
                                           unsigned int sid_ctx_len)
4069
    {
4070
        WOLFSSL_ENTER("wolfSSL_CTX_set_session_id_context");
4071
4072
        /* No application specific context needed for wolfSSL */
4073
        if (sid_ctx_len > ID_LEN || ctx == NULL || sid_ctx == NULL) {
4074
            return WOLFSSL_FAILURE;
4075
        }
4076
        XMEMCPY(ctx->sessionCtx, sid_ctx, sid_ctx_len);
4077
        ctx->sessionCtxSz = (byte)sid_ctx_len;
4078
4079
        return WOLFSSL_SUCCESS;
4080
    }
4081
4082
4083
4084
    /* Storing app session context id. Any session that is imported with a
4085
     * different session context id will be rejected.
4086
     *
4087
     * ssl  structure to set context in
4088
     * id   value of context to set
4089
     * len  length of sid_ctx buffer
4090
     *
4091
     * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing
4092
     */
4093
    int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id,
4094
                                   unsigned int len)
4095
    {
4096
        WOLFSSL_ENTER("wolfSSL_set_session_id_context");
4097
4098
        if (len > ID_LEN || ssl == NULL || id == NULL) {
4099
            return WOLFSSL_FAILURE;
4100
        }
4101
        XMEMCPY(ssl->sessionCtx, id, len);
4102
        ssl->sessionCtxSz = (byte)len;
4103
4104
        return WOLFSSL_SUCCESS;
4105
    }
4106
#endif
4107
4108
/* return a new malloc'd session with default settings on success */
4109
WOLFSSL_SESSION* wolfSSL_NewSession(void* heap)
4110
0
{
4111
0
    WOLFSSL_SESSION* ret = NULL;
4112
4113
0
    WOLFSSL_ENTER("wolfSSL_NewSession");
4114
4115
0
    ret = (WOLFSSL_SESSION*)XMALLOC(sizeof(WOLFSSL_SESSION), heap,
4116
0
            DYNAMIC_TYPE_SESSION);
4117
0
    if (ret != NULL) {
4118
0
        int err;
4119
0
        XMEMSET(ret, 0, sizeof(WOLFSSL_SESSION));
4120
0
        wolfSSL_RefInit(&ret->ref, &err);
4121
    #ifdef WOLFSSL_REFCNT_ERROR_RETURN
4122
        if (err != 0) {
4123
            WOLFSSL_MSG("Error setting up session reference mutex");
4124
            XFREE(ret, ret->heap, DYNAMIC_TYPE_SESSION);
4125
            return NULL;
4126
        }
4127
    #else
4128
0
        (void)err;
4129
0
    #endif
4130
0
#ifndef NO_SESSION_CACHE
4131
0
        ret->cacheRow = INVALID_SESSION_ROW; /* not in cache */
4132
0
#endif
4133
0
        ret->type = WOLFSSL_SESSION_TYPE_HEAP;
4134
0
        ret->heap = heap;
4135
#ifdef WOLFSSL_CHECK_MEM_ZERO
4136
        wc_MemZero_Add("SESSION master secret", ret->masterSecret, SECRET_LEN);
4137
        wc_MemZero_Add("SESSION id", ret->sessionID, ID_LEN);
4138
#endif
4139
    #ifdef HAVE_SESSION_TICKET
4140
        ret->ticket = ret->staticTicket;
4141
        #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&  \
4142
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
4143
        ret->ticketNonce.data = ret->ticketNonce.dataStatic;
4144
        #endif
4145
    #endif
4146
#ifdef HAVE_EX_DATA
4147
        ret->ownExData = 1;
4148
        #ifdef HAVE_EX_DATA_CRYPTO
4149
        if (crypto_ex_cb_ctx_session != NULL) {
4150
            crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session,
4151
                    &ret->ex_data);
4152
        }
4153
        #endif
4154
#endif
4155
0
    }
4156
0
    return ret;
4157
0
}
4158
4159
4160
WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap)
4161
0
{
4162
0
    return wolfSSL_NewSession(heap);
4163
0
}
4164
4165
WOLFSSL_SESSION* wolfSSL_SESSION_new(void)
4166
0
{
4167
0
    return wolfSSL_SESSION_new_ex(NULL);
4168
0
}
4169
4170
/* add one to session reference count
4171
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */
4172
int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session)
4173
0
{
4174
0
    int ret;
4175
4176
0
    session = ClientSessionToSession(session);
4177
4178
0
    if (session == NULL || session->type != WOLFSSL_SESSION_TYPE_HEAP)
4179
0
        return WOLFSSL_FAILURE;
4180
4181
0
    wolfSSL_RefInc(&session->ref, &ret);
4182
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
4183
    if (ret != 0) {
4184
        WOLFSSL_MSG("Failed to lock session mutex");
4185
        return WOLFSSL_FAILURE;
4186
    }
4187
#else
4188
0
    (void)ret;
4189
0
#endif
4190
4191
0
    return WOLFSSL_SUCCESS;
4192
0
}
4193
4194
/**
4195
 * Deep copy the contents from input to output.
4196
 * @param input         The source of the copy.
4197
 * @param output        The destination of the copy.
4198
 * @param avoidSysCalls If true, then system calls will be avoided or an error
4199
 *                      will be returned if it is not possible to proceed
4200
 *                      without a system call. This is useful for fetching
4201
 *                      sessions from cache. When a cache row is locked, we
4202
 *                      don't want to block other threads with long running
4203
 *                      system calls.
4204
 * @param transferExData If true, the output takes over the input's ex_data.
4205
 *                      Set false when the caller keeps the output and the
4206
 *                      input's ex_data stays owned elsewhere, e.g. the cache.
4207
 * @param ticketNonceBuf If not null and @avoidSysCalls is true, the copy of the
4208
 *                      ticketNonce will happen in this pre allocated buffer
4209
 * @param ticketNonceLen @ticketNonceBuf len as input, used length on output
4210
 * @param ticketNonceUsed if @ticketNonceBuf was used to copy the ticket nonce
4211
 * @return              WOLFSSL_SUCCESS on success
4212
 *                      WOLFSSL_FAILURE on failure
4213
 */
4214
static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input,
4215
    WOLFSSL_SESSION* output, int avoidSysCalls, int transferExData,
4216
    byte* ticketNonceBuf, byte* ticketNonceLen, byte* preallocUsed)
4217
0
{
4218
#ifdef HAVE_SESSION_TICKET
4219
    word16 ticLenAlloc = 0;
4220
    byte *ticBuff = NULL;
4221
#endif
4222
#ifdef HAVE_EX_DATA
4223
    WOLFSSL_CRYPTO_EX_DATA exData;
4224
#endif
4225
0
    const size_t copyOffset = WC_OFFSETOF(WOLFSSL_SESSION, heap) +
4226
0
        sizeof(input->heap);
4227
0
    int ret = WOLFSSL_SUCCESS;
4228
4229
0
    (void)avoidSysCalls;
4230
0
    (void)transferExData;
4231
0
    (void)ticketNonceBuf;
4232
0
    (void)ticketNonceLen;
4233
0
    (void)preallocUsed;
4234
4235
0
    input = ClientSessionToSession(input);
4236
0
    output = ClientSessionToSession(output);
4237
4238
0
    if (input == NULL || output == NULL || input == output) {
4239
0
        WOLFSSL_MSG("input or output are null or same");
4240
0
        return WOLFSSL_FAILURE;
4241
0
    }
4242
4243
#ifdef HAVE_SESSION_TICKET
4244
    if (output->ticket != output->staticTicket) {
4245
        ticBuff = output->ticket;
4246
        ticLenAlloc = output->ticketLenAlloc;
4247
    }
4248
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
4249
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
4250
        /* free the data, it would be better to reuse the buffer but this
4251
         * maintain the code simpler. A smart allocator should reuse the free'd
4252
         * buffer in the next malloc without much performance penalties. */
4253
    if (output->ticketNonce.data != output->ticketNonce.dataStatic) {
4254
4255
        /*  Callers that avoid syscall should never calls this with
4256
         * output->tickeNonce.data being a dynamic buffer.*/
4257
        if (avoidSysCalls) {
4258
            WOLFSSL_MSG("can't avoid syscalls with dynamic TicketNonce buffer");
4259
            return WOLFSSL_FAILURE;
4260
        }
4261
4262
        XFREE(output->ticketNonce.data,
4263
            output->heap, DYNAMIC_TYPE_SESSION_TICK);
4264
        output->ticketNonce.data = output->ticketNonce.dataStatic;
4265
        output->ticketNonce.len = 0;
4266
    }
4267
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
4268
#endif /* HAVE_SESSION_TICKET */
4269
4270
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
4271
    if (output->peer != NULL) {
4272
        if (avoidSysCalls) {
4273
            WOLFSSL_MSG("Can't free cert when avoiding syscalls");
4274
            return WOLFSSL_FAILURE;
4275
        }
4276
        wolfSSL_X509_free(output->peer);
4277
        output->peer = NULL;
4278
    }
4279
#endif
4280
4281
#ifdef HAVE_EX_DATA
4282
    /* ex_data sits after the heap member so the copy below carries over the
4283
     * input's pointers. Stash the output's to put them back. */
4284
    if (!transferExData)
4285
        XMEMCPY(&exData, &output->ex_data, sizeof(exData));
4286
#endif
4287
4288
0
    XMEMCPY((byte*)output + copyOffset, (byte*)input + copyOffset,
4289
0
            sizeof(WOLFSSL_SESSION) - copyOffset);
4290
4291
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) &&                  \
4292
    defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
4293
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
4294
    /* fix pointer to static after the copy  */
4295
    output->ticketNonce.data = output->ticketNonce.dataStatic;
4296
#endif
4297
    /* Set sane values for copy */
4298
0
#ifndef NO_SESSION_CACHE
4299
0
    if (output->type != WOLFSSL_SESSION_TYPE_CACHE)
4300
0
        output->cacheRow = INVALID_SESSION_ROW;
4301
0
#endif
4302
#ifdef HAVE_SESSION_TICKET
4303
    if (input->ticketLen > SESSION_TICKET_LEN) {
4304
        /* Need dynamic buffer */
4305
        if (ticBuff == NULL || ticLenAlloc < input->ticketLen) {
4306
            /* allocate new one */
4307
            byte* tmp;
4308
            if (avoidSysCalls) {
4309
                WOLFSSL_MSG("Failed to allocate memory for ticket when avoiding"
4310
                        " syscalls");
4311
                output->ticket = ticBuff;
4312
                output->ticketLenAlloc = (word16) ticLenAlloc;
4313
                output->ticketLen = 0;
4314
                ret = WOLFSSL_FAILURE;
4315
            }
4316
            else {
4317
#ifdef WOLFSSL_NO_REALLOC
4318
                tmp = (byte*)XMALLOC(input->ticketLen,
4319
                        output->heap, DYNAMIC_TYPE_SESSION_TICK);
4320
                XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK);
4321
                ticBuff = NULL;
4322
#else
4323
                tmp = (byte*)XREALLOC(ticBuff, input->ticketLen,
4324
                        output->heap, DYNAMIC_TYPE_SESSION_TICK);
4325
#endif /* WOLFSSL_NO_REALLOC */
4326
                if (tmp == NULL) {
4327
                    WOLFSSL_MSG("Failed to allocate memory for ticket");
4328
#ifndef WOLFSSL_NO_REALLOC
4329
                    XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK);
4330
                    ticBuff = NULL;
4331
#endif /* WOLFSSL_NO_REALLOC */
4332
                    output->ticket = NULL;
4333
                    output->ticketLen = 0;
4334
                    output->ticketLenAlloc = 0;
4335
                    ret = WOLFSSL_FAILURE;
4336
                }
4337
                else {
4338
                    ticBuff = tmp;
4339
                    ticLenAlloc = input->ticketLen;
4340
                }
4341
            }
4342
        }
4343
        if (ticBuff != NULL && ret == WOLFSSL_SUCCESS) {
4344
            XMEMCPY(ticBuff, input->ticket, input->ticketLen);
4345
            output->ticket = ticBuff;
4346
            output->ticketLenAlloc = (word16) ticLenAlloc;
4347
        }
4348
    }
4349
    else {
4350
        /* Default ticket to non dynamic */
4351
        if (avoidSysCalls) {
4352
            /* Try to use ticBuf if available. Caller can later move it to
4353
             * the static buffer. */
4354
            if (ticBuff != NULL) {
4355
                if (ticLenAlloc >= input->ticketLen) {
4356
                    output->ticket = ticBuff;
4357
                    output->ticketLenAlloc = ticLenAlloc;
4358
                }
4359
                else {
4360
                    WOLFSSL_MSG("ticket dynamic buffer too small but we are "
4361
                                "avoiding system calls");
4362
                    ret = WOLFSSL_FAILURE;
4363
                    output->ticket = ticBuff;
4364
                    output->ticketLenAlloc = (word16) ticLenAlloc;
4365
                    output->ticketLen = 0;
4366
                }
4367
            }
4368
            else {
4369
                output->ticket = output->staticTicket;
4370
                output->ticketLenAlloc = 0;
4371
            }
4372
        }
4373
        else {
4374
            XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK);
4375
            output->ticket = output->staticTicket;
4376
            output->ticketLenAlloc = 0;
4377
        }
4378
        if (input->ticketLen > 0 && ret == WOLFSSL_SUCCESS) {
4379
            /* Output may be a reused buffer, not a copy of input's */
4380
            XMEMCPY(output->ticket, input->ticket,
4381
                    input->ticketLen);
4382
        }
4383
    }
4384
    ticBuff = NULL;
4385
4386
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
4387
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
4388
    if (preallocUsed != NULL)
4389
        *preallocUsed = 0;
4390
4391
    if (input->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ &&
4392
        ret == WOLFSSL_SUCCESS) {
4393
        /* TicketNonce does not fit in the static buffer */
4394
        if (!avoidSysCalls) {
4395
            output->ticketNonce.data = (byte*)XMALLOC(input->ticketNonce.len,
4396
                output->heap, DYNAMIC_TYPE_SESSION_TICK);
4397
4398
            if (output->ticketNonce.data == NULL) {
4399
                WOLFSSL_MSG("Failed to allocate space for ticket nonce");
4400
                output->ticketNonce.data = output->ticketNonce.dataStatic;
4401
                output->ticketNonce.len = 0;
4402
                ret = WOLFSSL_FAILURE;
4403
            }
4404
            else {
4405
                output->ticketNonce.len = input->ticketNonce.len;
4406
                XMEMCPY(output->ticketNonce.data, input->ticketNonce.data,
4407
                    input->ticketNonce.len);
4408
                ret = WOLFSSL_SUCCESS;
4409
            }
4410
        }
4411
        /* we can't do syscalls. Use prealloc buffers if provided from the
4412
         * caller. */
4413
        else if (ticketNonceBuf != NULL &&
4414
                 *ticketNonceLen >= input->ticketNonce.len) {
4415
            XMEMCPY(ticketNonceBuf, input->ticketNonce.data,
4416
                input->ticketNonce.len);
4417
            *ticketNonceLen = input->ticketNonce.len;
4418
            if (preallocUsed != NULL)
4419
                *preallocUsed = 1;
4420
            ret = WOLFSSL_SUCCESS;
4421
        }
4422
        else {
4423
            WOLFSSL_MSG("TicketNonce bigger than static buffer, and we can't "
4424
                        "do syscalls");
4425
            ret = WOLFSSL_FAILURE;
4426
        }
4427
    }
4428
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
4429
4430
#endif /* HAVE_SESSION_TICKET */
4431
4432
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
4433
    /* After the ticket so a failure here can't leave it aliasing input's */
4434
    if (input->peer != NULL && input->peer->dynamicMemory) {
4435
        if (wolfSSL_X509_up_ref(input->peer) != WOLFSSL_SUCCESS) {
4436
            WOLFSSL_MSG("Can't increase peer cert ref count");
4437
            output->peer = NULL;
4438
            ret = WOLFSSL_FAILURE;
4439
        }
4440
    }
4441
    else if (!avoidSysCalls) {
4442
        output->peer = wolfSSL_X509_dup(input->peer);
4443
        if (input->peer != NULL && output->peer == NULL)
4444
            ret = WOLFSSL_FAILURE;
4445
    }
4446
    else
4447
        /* output->peer is not that important to copy */
4448
        output->peer = NULL;
4449
#endif
4450
4451
#ifdef HAVE_EX_DATA_CRYPTO
4452
    if (ret == WOLFSSL_SUCCESS && transferExData &&
4453
            input->type != WOLFSSL_SESSION_TYPE_CACHE &&
4454
            output->type != WOLFSSL_SESSION_TYPE_CACHE) {
4455
        /* Not called with cache as that passes ownership of ex_data */
4456
        ret = crypto_ex_cb_dup_data(&input->ex_data, &output->ex_data,
4457
                                    crypto_ex_cb_ctx_session);
4458
    }
4459
#endif
4460
4461
#ifdef HAVE_EX_DATA
4462
    if (!transferExData)
4463
        XMEMCPY(&output->ex_data, &exData, sizeof(exData));
4464
#endif
4465
4466
0
    return ret;
4467
0
}
4468
4469
/**
4470
 * Deep copy the contents from input to output.
4471
 * @param input         The source of the copy.
4472
 * @param output        The destination of the copy.
4473
 * @param avoidSysCalls If true, then system calls will be avoided or an error
4474
 *                      will be returned if it is not possible to proceed
4475
 *                      without a system call. This is useful for fetching
4476
 *                      sessions from cache. When a cache row is locked, we
4477
 *                      don't want to block other threads with long running
4478
 *                      system calls.
4479
 * @return              WOLFSSL_SUCCESS on success
4480
 *                      WOLFSSL_FAILURE on failure
4481
 */
4482
int wolfSSL_DupSession(const WOLFSSL_SESSION* input, WOLFSSL_SESSION* output,
4483
        int avoidSysCalls)
4484
0
{
4485
0
    return wolfSSL_DupSessionEx(input, output, avoidSysCalls, 1, NULL, NULL,
4486
0
        NULL);
4487
0
}
4488
4489
WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session)
4490
0
{
4491
0
    WOLFSSL_SESSION* copy;
4492
4493
0
    WOLFSSL_ENTER("wolfSSL_SESSION_dup");
4494
4495
0
    session = ClientSessionToSession(session);
4496
0
    if (session == NULL)
4497
0
        return NULL;
4498
4499
#ifdef HAVE_SESSION_TICKET
4500
    if (session->ticketLenAlloc > 0 && !session->ticket) {
4501
        WOLFSSL_MSG("Session dynamic flag is set but ticket pointer is null");
4502
        return NULL;
4503
    }
4504
#endif
4505
4506
0
    copy = wolfSSL_NewSession(session->heap);
4507
0
    if (copy != NULL &&
4508
0
            wolfSSL_DupSession(session, copy, 0) != WOLFSSL_SUCCESS) {
4509
0
        wolfSSL_FreeSession(NULL, copy);
4510
0
        copy = NULL;
4511
0
    }
4512
0
    return copy;
4513
0
}
4514
4515
void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session)
4516
{
4517
    session = ClientSessionToSession(session);
4518
    if (session == NULL)
4519
        return;
4520
4521
    (void)ctx;
4522
4523
    WOLFSSL_ENTER("wolfSSL_FreeSession");
4524
4525
    if (session->ref.count > 0) {
4526
        int ret;
4527
        int isZero;
4528
        wolfSSL_RefDec(&session->ref, &isZero, &ret);
4529
        (void)ret;
4530
        if (!isZero) {
4531
            return;
4532
        }
4533
        wolfSSL_RefFree(&session->ref);
4534
    }
4535
4536
    WOLFSSL_MSG("wolfSSL_FreeSession full free");
4537
4538
#ifdef HAVE_EX_DATA_CRYPTO
4539
    if (session->ownExData) {
4540
        crypto_ex_cb_free_data(session, crypto_ex_cb_ctx_session,
4541
                &session->ex_data);
4542
    }
4543
#endif
4544
4545
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
4546
    wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data);
4547
#endif
4548
4549
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
4550
    if (session->peer) {
4551
        wolfSSL_X509_free(session->peer);
4552
        session->peer = NULL;
4553
    }
4554
#endif
4555
4556
#ifdef HAVE_SESSION_TICKET
4557
    if (session->ticketLenAlloc > 0) {
4558
        XFREE(session->ticket, session->heap, DYNAMIC_TYPE_SESSION_TICK);
4559
        session->ticket = session->staticTicket;
4560
        session->ticketLen = 0;
4561
        session->ticketLenAlloc = 0;
4562
    }
4563
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&          \
4564
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
4565
    if (session->ticketNonce.data != session->ticketNonce.dataStatic) {
4566
        XFREE(session->ticketNonce.data, session->heap,
4567
            DYNAMIC_TYPE_SESSION_TICK);
4568
        session->ticketNonce.data = session->ticketNonce.dataStatic;
4569
        session->ticketNonce.len = 0;
4570
    }
4571
#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/
4572
#endif
4573
4574
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
4575
    wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data);
4576
#endif
4577
4578
    /* Make sure masterSecret is zeroed. */
4579
    ForceZero(session->masterSecret, SECRET_LEN);
4580
    /* Session ID is sensitive information too. */
4581
    ForceZero(session->sessionID, ID_LEN);
4582
4583
    if (session->type == WOLFSSL_SESSION_TYPE_HEAP) {
4584
        /* // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) */
4585
        XFREE(session, session->heap, DYNAMIC_TYPE_SESSION);
4586
    }
4587
}
4588
4589
/* DO NOT use this API internally. Use wolfSSL_FreeSession directly instead
4590
 * and pass in the ctx parameter if possible (like from ssl->ctx). */
4591
void wolfSSL_SESSION_free(WOLFSSL_SESSION* session)
4592
0
{
4593
0
    session = ClientSessionToSession(session);
4594
0
    wolfSSL_FreeSession(NULL, session);
4595
0
}
4596
4597
#if defined(OPENSSL_EXTRA) || defined(HAVE_EXT_CACHE)
4598
4599
/**
4600
* set cipher to WOLFSSL_SESSION from WOLFSSL_CIPHER
4601
* @param session  a pointer to WOLFSSL_SESSION structure
4602
* @param cipher   a function pointer to WOLFSSL_CIPHER
4603
* @return WOLFSSL_SUCCESS on success, otherwise WOLFSSL_FAILURE
4604
*/
4605
int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session,
4606
                                            const WOLFSSL_CIPHER* cipher)
4607
{
4608
    WOLFSSL_ENTER("wolfSSL_SESSION_set_cipher");
4609
4610
    session = ClientSessionToSession(session);
4611
    /* sanity check */
4612
    if (session == NULL || cipher == NULL) {
4613
        WOLFSSL_MSG("bad argument");
4614
        return WOLFSSL_FAILURE;
4615
    }
4616
    session->cipherSuite0 = cipher->cipherSuite0;
4617
    session->cipherSuite  = cipher->cipherSuite;
4618
4619
    WOLFSSL_LEAVE("wolfSSL_SESSION_set_cipher", WOLFSSL_SUCCESS);
4620
    return WOLFSSL_SUCCESS;
4621
}
4622
#endif /* OPENSSL_EXTRA || HAVE_EXT_CACHE */
4623
4624
const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session)
4625
0
{
4626
0
    session = ClientSessionToSession(session);
4627
0
    if (session == NULL) {
4628
0
        return NULL;
4629
0
    }
4630
4631
0
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
4632
0
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
4633
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS)
4634
0
        return GetCipherNameIana(session->cipherSuite0, session->cipherSuite);
4635
    #else
4636
        return GetCipherNameInternal(session->cipherSuite0,
4637
            session->cipherSuite);
4638
    #endif
4639
#else
4640
    return NULL;
4641
#endif
4642
0
}
4643
4644
#if defined(OPENSSL_ALL) || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)
4645
const unsigned char *wolfSSL_SESSION_get0_id_context(
4646
                      const WOLFSSL_SESSION *sess, unsigned int *sid_ctx_length)
4647
{
4648
    return wolfSSL_SESSION_get_id((WOLFSSL_SESSION *)sess, sid_ctx_length);
4649
}
4650
int wolfSSL_SESSION_set1_id(WOLFSSL_SESSION *s,
4651
                                 const unsigned char *sid, unsigned int sid_len)
4652
{
4653
    WOLFSSL_SESSION* sess = ClientSessionToSession(s);
4654
4655
    if (sess == NULL) {
4656
        return WOLFSSL_FAILURE;
4657
    }
4658
    if (sid_len > ID_LEN) {
4659
        return WOLFSSL_FAILURE;
4660
    }
4661
    if (sess != s) {
4662
        /* A client cache handle is keyed by its ID, so it can't change. */
4663
        if (sid_len == sess->sessionIDSz &&
4664
                XMEMCMP(sid, sess->sessionID, sid_len) == 0) {
4665
            return WOLFSSL_SUCCESS;
4666
        }
4667
        return WOLFSSL_FAILURE;
4668
    }
4669
4670
    sess->sessionIDSz = (byte)sid_len;
4671
    if (sid != sess->sessionID) {
4672
        XMEMCPY(sess->sessionID, sid, sid_len);
4673
    }
4674
    return WOLFSSL_SUCCESS;
4675
}
4676
4677
int wolfSSL_SESSION_set1_id_context(WOLFSSL_SESSION *s,
4678
                         const unsigned char *sid_ctx, unsigned int sid_ctx_len)
4679
{
4680
    s = ClientSessionToSession(s);
4681
    if (s == NULL) {
4682
        return WOLFSSL_FAILURE;
4683
    }
4684
    if (sid_ctx_len > ID_LEN) {
4685
        return WOLFSSL_FAILURE;
4686
    }
4687
    s->sessionCtxSz = (byte)sid_ctx_len;
4688
    if (sid_ctx != s->sessionCtx) {
4689
        XMEMCPY(s->sessionCtx, sid_ctx, sid_ctx_len);
4690
    }
4691
4692
    return WOLFSSL_SUCCESS;
4693
}
4694
4695
#endif
4696
4697
#ifdef OPENSSL_EXTRA
4698
4699
/* Return the total number of sessions */
4700
long wolfSSL_CTX_sess_number(WOLFSSL_CTX* ctx)
4701
{
4702
    word32 total = 0;
4703
4704
    WOLFSSL_ENTER("wolfSSL_CTX_sess_number");
4705
    (void)ctx;
4706
4707
#if defined(WOLFSSL_SESSION_STATS) && !defined(NO_SESSION_CACHE)
4708
    if (wolfSSL_get_session_stats(NULL, &total, NULL, NULL) !=
4709
            WOLFSSL_SUCCESS) {
4710
        WOLFSSL_MSG("Error getting session stats");
4711
    }
4712
#else
4713
    WOLFSSL_MSG("Please use macro WOLFSSL_SESSION_STATS for session stats");
4714
#endif
4715
4716
    return (long)total;
4717
}
4718
4719
#endif
4720
4721
#ifdef SESSION_CERTS
4722
4723
/* get session ID */
4724
WOLFSSL_ABI
4725
const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session)
4726
{
4727
    WOLFSSL_ENTER("wolfSSL_get_sessionID");
4728
    session = ClientSessionToSession(session);
4729
    if (session)
4730
        return session->sessionID;
4731
4732
    return NULL;
4733
}
4734
4735
#endif
4736
4737
#ifdef HAVE_EX_DATA
4738
4739
int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data)
4740
{
4741
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
4742
    WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data");
4743
#ifdef HAVE_EX_DATA
4744
    session = ClientSessionToSession(session);
4745
    if (session != NULL) {
4746
#ifndef NO_SESSION_CACHE
4747
        if (!session->ownExData) {
4748
            /* Need to update in cache */
4749
            SESSION_ex_data_cache_update(session, idx, data, 0, NULL, &ret);
4750
        }
4751
        else
4752
#endif
4753
        {
4754
            ret = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, data);
4755
        }
4756
    }
4757
#else
4758
    (void)session;
4759
    (void)idx;
4760
    (void)data;
4761
#endif
4762
    return ret;
4763
}
4764
4765
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
4766
int wolfSSL_SESSION_set_ex_data_with_cleanup(
4767
    WOLFSSL_SESSION* session,
4768
    int idx,
4769
    void* data,
4770
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
4771
{
4772
    WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data_with_cleanup");
4773
    session = ClientSessionToSession(session);
4774
    if(session != NULL) {
4775
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&session->ex_data, idx,
4776
                                                       data, cleanup_routine);
4777
    }
4778
    return WOLFSSL_FAILURE;
4779
}
4780
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
4781
4782
void* wolfSSL_SESSION_get_ex_data(const WOLFSSL_SESSION* session, int idx)
4783
{
4784
    void* ret = NULL;
4785
    WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_data");
4786
#ifdef HAVE_EX_DATA
4787
    session = ClientSessionToSession(session);
4788
    if (session != NULL) {
4789
#ifndef NO_SESSION_CACHE
4790
        if (!session->ownExData) {
4791
            /* Need to retrieve the data from the session cache */
4792
            SESSION_ex_data_cache_update((WOLFSSL_SESSION*)session, idx, NULL,
4793
                                         1, &ret, NULL);
4794
        }
4795
        else
4796
#endif
4797
        {
4798
            ret = wolfSSL_CRYPTO_get_ex_data(&session->ex_data, idx);
4799
        }
4800
    }
4801
#else
4802
    (void)session;
4803
    (void)idx;
4804
#endif
4805
    return ret;
4806
}
4807
4808
#ifdef HAVE_EX_DATA_CRYPTO
4809
int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr,
4810
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
4811
        WOLFSSL_CRYPTO_EX_free* free_func)
4812
{
4813
    WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_new_index");
4814
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_SESSION,
4815
            ctx_l, ctx_ptr, new_func, dup_func, free_func);
4816
}
4817
#endif /* HAVE_EX_DATA_CRYPTO */
4818
#endif /* HAVE_EX_DATA */
4819
4820
#if defined(OPENSSL_ALL) || \
4821
    defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \
4822
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
4823
4824
const byte* wolfSSL_SESSION_get_id(const WOLFSSL_SESSION* sess,
4825
        unsigned int* idLen)
4826
{
4827
    WOLFSSL_ENTER("wolfSSL_SESSION_get_id");
4828
    sess = ClientSessionToSession(sess);
4829
    if (sess == NULL || idLen == NULL) {
4830
        WOLFSSL_MSG("Bad func args. Please provide idLen");
4831
        return NULL;
4832
    }
4833
#ifdef HAVE_SESSION_TICKET
4834
    if (sess->haveAltSessionID) {
4835
        *idLen = ID_LEN;
4836
        return sess->altSessionID;
4837
    }
4838
#endif
4839
    *idLen = sess->sessionIDSz;
4840
    return sess->sessionID;
4841
}
4842
4843
#if (defined(HAVE_SESSION_TICKET) || defined(SESSION_CERTS)) && \
4844
    !defined(NO_FILESYSTEM)
4845
4846
#ifndef NO_BIO
4847
4848
#if defined(SESSION_CERTS) || \
4849
   (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
4850
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version);
4851
4852
/* returns a pointer to the protocol used by the session */
4853
static const char* wolfSSL_SESSION_get_protocol(const WOLFSSL_SESSION* in)
4854
{
4855
    in = ClientSessionToSession(in);
4856
    return wolfSSL_internal_get_version((ProtocolVersion*)&in->version);
4857
}
4858
#endif
4859
4860
/* returns true (non 0) if the session has EMS (extended master secret) */
4861
static int wolfSSL_SESSION_haveEMS(const WOLFSSL_SESSION* in)
4862
{
4863
    in = ClientSessionToSession(in);
4864
    if (in == NULL)
4865
        return 0;
4866
    return in->haveEMS;
4867
}
4868
4869
#if defined(HAVE_SESSION_TICKET)
4870
/* prints out the ticket to bio passed in
4871
 * return WOLFSSL_SUCCESS on success
4872
 */
4873
static int wolfSSL_SESSION_print_ticket(WOLFSSL_BIO* bio,
4874
        const WOLFSSL_SESSION* in, const char* tab)
4875
{
4876
    unsigned short i, j, z, sz;
4877
    short tag = 0;
4878
    byte* pt;
4879
4880
4881
    in = ClientSessionToSession(in);
4882
    if (in == NULL || bio == NULL) {
4883
        return BAD_FUNC_ARG;
4884
    }
4885
4886
    sz = in->ticketLen;
4887
    pt = in->ticket;
4888
4889
    if (wolfSSL_BIO_printf(bio, "%s\n", (sz == 0)? " NONE": "") <= 0)
4890
        return WOLFSSL_FAILURE;
4891
4892
    for (i = 0; i < sz;) {
4893
        char asc[16];
4894
        XMEMSET(asc, 0, sizeof(asc));
4895
4896
        if (sz - i < 16) {
4897
            if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag + (sz - i)) <= 0)
4898
                return WOLFSSL_FAILURE;
4899
        }
4900
        else {
4901
            if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag) <= 0)
4902
                return WOLFSSL_FAILURE;
4903
        }
4904
        for (j = 0; i < sz && j < 8; j++,i++) {
4905
            asc[j] =  ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
4906
            if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0)
4907
                return WOLFSSL_FAILURE;
4908
        }
4909
4910
        if (i < sz) {
4911
            asc[j] =  ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
4912
            if (wolfSSL_BIO_printf(bio, "-%02X", pt[i]) <= 0)
4913
                return WOLFSSL_FAILURE;
4914
            j++;
4915
            i++;
4916
        }
4917
4918
        for (; i < sz && j < 16; j++,i++) {
4919
            asc[j] =  ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.';
4920
            if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0)
4921
                return WOLFSSL_FAILURE;
4922
        }
4923
4924
        /* pad out spacing */
4925
        for (z = j; z < 17; z++) {
4926
            if (wolfSSL_BIO_printf(bio, "   ") <= 0)
4927
                return WOLFSSL_FAILURE;
4928
        }
4929
4930
        for (z = 0; z < j; z++) {
4931
            if (wolfSSL_BIO_printf(bio, "%c", asc[z]) <= 0)
4932
                return WOLFSSL_FAILURE;
4933
        }
4934
        if (wolfSSL_BIO_printf(bio, "\n") <= 0)
4935
            return WOLFSSL_FAILURE;
4936
4937
        tag += 16;
4938
    }
4939
    return WOLFSSL_SUCCESS;
4940
}
4941
#endif /* HAVE_SESSION_TICKET */
4942
4943
4944
/* prints out the session information in human readable form
4945
 * return WOLFSSL_SUCCESS on success
4946
 */
4947
int wolfSSL_SESSION_print(WOLFSSL_BIO *bp, const WOLFSSL_SESSION *session)
4948
{
4949
    const unsigned char* pt;
4950
    unsigned char buf[SECRET_LEN];
4951
    unsigned int sz = 0, i;
4952
    int ret;
4953
4954
    session = ClientSessionToSession(session);
4955
    if (session == NULL) {
4956
        return WOLFSSL_FAILURE;
4957
    }
4958
4959
    if (wolfSSL_BIO_printf(bp, "%s\n", "SSL-Session:") <= 0)
4960
        return WOLFSSL_FAILURE;
4961
4962
#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \
4963
                               defined(HAVE_SESSION_TICKET))
4964
    if (wolfSSL_BIO_printf(bp, "    Protocol  : %s\n",
4965
            wolfSSL_SESSION_get_protocol(session)) <= 0)
4966
        return WOLFSSL_FAILURE;
4967
#endif
4968
4969
    if (wolfSSL_BIO_printf(bp, "    Cipher    : %s\n",
4970
            wolfSSL_SESSION_CIPHER_get_name(session)) <= 0)
4971
        return WOLFSSL_FAILURE;
4972
4973
    pt = wolfSSL_SESSION_get_id(session, &sz);
4974
    if (wolfSSL_BIO_printf(bp, "    Session-ID: ") <= 0)
4975
        return WOLFSSL_FAILURE;
4976
4977
    for (i = 0; i < sz; i++) {
4978
        if (wolfSSL_BIO_printf(bp, "%02X", pt[i]) <= 0)
4979
            return WOLFSSL_FAILURE;
4980
    }
4981
    if (wolfSSL_BIO_printf(bp, "\n") <= 0)
4982
        return WOLFSSL_FAILURE;
4983
4984
    if (wolfSSL_BIO_printf(bp, "    Session-ID-ctx: \n") <= 0)
4985
        return WOLFSSL_FAILURE;
4986
4987
    ret = wolfSSL_SESSION_get_master_key(session, buf, sizeof(buf));
4988
    if (wolfSSL_BIO_printf(bp, "    Master-Key: ") <= 0)
4989
        return WOLFSSL_FAILURE;
4990
4991
    if (ret > 0) {
4992
        sz = (unsigned int)ret;
4993
        for (i = 0; i < sz; i++) {
4994
            if (wolfSSL_BIO_printf(bp, "%02X", buf[i]) <= 0)
4995
                return WOLFSSL_FAILURE;
4996
        }
4997
    }
4998
    if (wolfSSL_BIO_printf(bp, "\n") <= 0)
4999
        return WOLFSSL_FAILURE;
5000
5001
    /* @TODO PSK identity hint and SRP */
5002
5003
    if (wolfSSL_BIO_printf(bp, "    TLS session ticket:") <= 0)
5004
        return WOLFSSL_FAILURE;
5005
5006
#ifdef HAVE_SESSION_TICKET
5007
    if (wolfSSL_SESSION_print_ticket(bp, session, "    ") != WOLFSSL_SUCCESS)
5008
        return WOLFSSL_FAILURE;
5009
#endif
5010
5011
#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \
5012
        defined(HAVE_EXT_CACHE))
5013
    if (wolfSSL_BIO_printf(bp, "    Start Time: %ld\n",
5014
                wolfSSL_SESSION_get_time(session)) <= 0)
5015
        return WOLFSSL_FAILURE;
5016
5017
    if (wolfSSL_BIO_printf(bp, "    Timeout   : %ld (sec)\n",
5018
            wolfSSL_SESSION_get_timeout(session)) <= 0)
5019
        return WOLFSSL_FAILURE;
5020
#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */
5021
5022
    /* @TODO verify return code print */
5023
5024
    if (wolfSSL_BIO_printf(bp, "    Extended master secret: %s\n",
5025
            (wolfSSL_SESSION_haveEMS(session) == 0)? "no" : "yes") <= 0)
5026
        return WOLFSSL_FAILURE;
5027
5028
    return WOLFSSL_SUCCESS;
5029
}
5030
5031
#endif /* !NO_BIO */
5032
#endif /* (HAVE_SESSION_TICKET || SESSION_CERTS) && !NO_FILESYSTEM */
5033
5034
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
5035
        * WOLFSSL_HAPROXY */
5036
5037
#ifdef OPENSSL_EXTRA
5038
/**
5039
 * Determine whether a WOLFSSL_SESSION object can be used for resumption
5040
 * @param s  a pointer to WOLFSSL_SESSION structure
5041
 * @return return 1 if session is resumable, otherwise 0.
5042
 */
5043
int wolfSSL_SESSION_is_resumable(const WOLFSSL_SESSION *s)
5044
{
5045
    s = ClientSessionToSession(s);
5046
    if (s == NULL)
5047
        return 0;
5048
5049
#ifdef HAVE_SESSION_TICKET
5050
    if (s->ticketLen > 0)
5051
        return 1;
5052
#endif
5053
5054
    if (s->sessionIDSz > 0)
5055
        return 1;
5056
5057
    return 0;
5058
}
5059
#endif /* OPENSSL_EXTRA */
5060
5061
#endif /* !WOLFSSL_SSL_SESS_INCLUDED */
5062