xref: /freebsd/crypto/openssl/ssl/ssl_sess.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2005 Nokia. All rights reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 #if defined(__TANDEM) && defined(_SPT_MODEL_)
12 #include <spthread.h>
13 #include <spt_extensions.h> /* timeval */
14 #endif
15 #include <stdio.h>
16 #include <openssl/rand.h>
17 #include <openssl/engine.h>
18 #include "internal/refcount.h"
19 #include "internal/cryptlib.h"
20 #include "internal/ssl_unwrap.h"
21 #include "ssl_local.h"
22 #include "statem/statem_local.h"
23 
24 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
25 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
26 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
27 
DEFINE_STACK_OF(SSL_SESSION)28 DEFINE_STACK_OF(SSL_SESSION)
29 
30 __owur static ossl_inline int sess_timedout(OSSL_TIME t, SSL_SESSION *ss)
31 {
32     return ossl_time_compare(t, ss->calc_timeout) > 0;
33 }
34 
35 /*
36  * Returns -1/0/+1 as other XXXcmp-type functions
37  * Takes calculated timeout into consideration
38  */
timeoutcmp(SSL_SESSION * a,SSL_SESSION * b)39 __owur static ossl_inline int timeoutcmp(SSL_SESSION *a, SSL_SESSION *b)
40 {
41     return ossl_time_compare(a->calc_timeout, b->calc_timeout);
42 }
43 
44 /*
45  * Calculates effective timeout
46  * Locking must be done by the caller of this function
47  */
ssl_session_calculate_timeout(SSL_SESSION * ss)48 void ssl_session_calculate_timeout(SSL_SESSION *ss)
49 {
50     ss->calc_timeout = ossl_time_add(ss->time, ss->timeout);
51 }
52 
53 /*
54  * SSL_get_session() and SSL_get1_session() are problematic in TLS1.3 because,
55  * unlike in earlier protocol versions, the session ticket may not have been
56  * sent yet even though a handshake has finished. The session ticket data could
57  * come in sometime later...or even change if multiple session ticket messages
58  * are sent from the server. The preferred way for applications to obtain
59  * a resumable session is to use SSL_CTX_sess_set_new_cb().
60  */
61 
SSL_get_session(const SSL * ssl)62 SSL_SESSION *SSL_get_session(const SSL *ssl)
63 /* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
64 {
65     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
66 
67     if (sc == NULL)
68         return NULL;
69 
70     return sc->session;
71 }
72 
SSL_get1_session(SSL * ssl)73 SSL_SESSION *SSL_get1_session(SSL *ssl)
74 /* variant of SSL_get_session: caller really gets something */
75 {
76     SSL_SESSION *sess;
77 
78     /*
79      * Need to lock this all up rather than just use CRYPTO_add so that
80      * somebody doesn't free ssl->session between when we check it's non-null
81      * and when we up the reference count.
82      */
83     if (!CRYPTO_THREAD_read_lock(ssl->lock))
84         return NULL;
85     sess = SSL_get_session(ssl);
86     if (sess != NULL && !SSL_SESSION_up_ref(sess))
87         sess = NULL;
88     CRYPTO_THREAD_unlock(ssl->lock);
89     return sess;
90 }
91 
SSL_SESSION_set_ex_data(SSL_SESSION * s,int idx,void * arg)92 int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
93 {
94     return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
95 }
96 
SSL_SESSION_get_ex_data(const SSL_SESSION * s,int idx)97 void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
98 {
99     return CRYPTO_get_ex_data(&s->ex_data, idx);
100 }
101 
SSL_SESSION_new(void)102 SSL_SESSION *SSL_SESSION_new(void)
103 {
104     SSL_SESSION *ss;
105 
106     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
107         return NULL;
108 
109     ss = OPENSSL_zalloc(sizeof(*ss));
110     if (ss == NULL)
111         return NULL;
112 
113     ss->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_UNSPECIFIED;
114     ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */
115     /* 5 minute timeout by default */
116     ss->timeout = ossl_seconds2time(60 * 5 + 4);
117     ss->time = ossl_time_now();
118     ssl_session_calculate_timeout(ss);
119     if (!CRYPTO_NEW_REF(&ss->references, 1)) {
120         OPENSSL_free(ss);
121         return NULL;
122     }
123 
124     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data)) {
125         CRYPTO_FREE_REF(&ss->references);
126         OPENSSL_free(ss);
127         return NULL;
128     }
129     return ss;
130 }
131 
132 /*
133  * Create a new SSL_SESSION and duplicate the contents of |src| into it. If
134  * ticket == 0 then no ticket information is duplicated, otherwise it is.
135  */
ssl_session_dup_intern(const SSL_SESSION * src,int ticket)136 static SSL_SESSION *ssl_session_dup_intern(const SSL_SESSION *src, int ticket)
137 {
138     SSL_SESSION *dest;
139 
140     dest = OPENSSL_malloc(sizeof(*dest));
141     if (dest == NULL)
142         return NULL;
143 
144     /*
145      * src is logically read-only but the prev/next pointers are not, they are
146      * part of the session cache and can be modified concurrently.
147      */
148     memcpy(dest, src, offsetof(SSL_SESSION, prev));
149 
150     /*
151      * Set the various pointers to NULL so that we can call SSL_SESSION_free in
152      * the case of an error whilst halfway through constructing dest
153      */
154 #ifndef OPENSSL_NO_PSK
155     dest->psk_identity_hint = NULL;
156     dest->psk_identity = NULL;
157 #endif
158     dest->ext.hostname = NULL;
159     dest->ext.tick = NULL;
160     dest->ext.alpn_selected = NULL;
161 #ifndef OPENSSL_NO_SRP
162     dest->srp_username = NULL;
163 #endif
164     dest->peer_chain = NULL;
165     dest->peer = NULL;
166     dest->peer_rpk = NULL;
167     dest->ticket_appdata = NULL;
168     memset(&dest->ex_data, 0, sizeof(dest->ex_data));
169 
170     /* As the copy is not in the cache, we remove the associated pointers */
171     dest->prev = NULL;
172     dest->next = NULL;
173     dest->owner = NULL;
174 
175     if (!CRYPTO_NEW_REF(&dest->references, 1)) {
176         OPENSSL_free(dest);
177         return NULL;
178     }
179 
180     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, dest, &dest->ex_data)) {
181         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
182         goto err;
183     }
184 
185     if (src->peer != NULL) {
186         if (!X509_up_ref(src->peer)) {
187             ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
188             goto err;
189         }
190         dest->peer = src->peer;
191     }
192 
193     if (src->peer_chain != NULL) {
194         dest->peer_chain = X509_chain_up_ref(src->peer_chain);
195         if (dest->peer_chain == NULL) {
196             ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);
197             goto err;
198         }
199     }
200 
201     if (src->peer_rpk != NULL) {
202         if (!EVP_PKEY_up_ref(src->peer_rpk))
203             goto err;
204         dest->peer_rpk = src->peer_rpk;
205     }
206 
207 #ifndef OPENSSL_NO_PSK
208     if (src->psk_identity_hint) {
209         dest->psk_identity_hint = OPENSSL_strdup(src->psk_identity_hint);
210         if (dest->psk_identity_hint == NULL)
211             goto err;
212     }
213     if (src->psk_identity) {
214         dest->psk_identity = OPENSSL_strdup(src->psk_identity);
215         if (dest->psk_identity == NULL)
216             goto err;
217     }
218 #endif
219 
220     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
221             &dest->ex_data, &src->ex_data)) {
222         ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
223         goto err;
224     }
225 
226     if (src->ext.hostname) {
227         dest->ext.hostname = OPENSSL_strdup(src->ext.hostname);
228         if (dest->ext.hostname == NULL)
229             goto err;
230     }
231 
232     if (ticket != 0 && src->ext.tick != NULL) {
233         dest->ext.tick = OPENSSL_memdup(src->ext.tick, src->ext.ticklen);
234         if (dest->ext.tick == NULL)
235             goto err;
236     } else {
237         dest->ext.tick_lifetime_hint = 0;
238         dest->ext.ticklen = 0;
239     }
240 
241     if (src->ext.alpn_selected != NULL) {
242         dest->ext.alpn_selected = OPENSSL_memdup(src->ext.alpn_selected,
243             src->ext.alpn_selected_len);
244         if (dest->ext.alpn_selected == NULL)
245             goto err;
246     }
247 
248 #ifndef OPENSSL_NO_SRP
249     if (src->srp_username) {
250         dest->srp_username = OPENSSL_strdup(src->srp_username);
251         if (dest->srp_username == NULL)
252             goto err;
253     }
254 #endif
255 
256     if (src->ticket_appdata != NULL) {
257         dest->ticket_appdata = OPENSSL_memdup(src->ticket_appdata, src->ticket_appdata_len);
258         if (dest->ticket_appdata == NULL)
259             goto err;
260     }
261 
262     return dest;
263 err:
264     SSL_SESSION_free(dest);
265     return NULL;
266 }
267 
SSL_SESSION_dup(const SSL_SESSION * src)268 SSL_SESSION *SSL_SESSION_dup(const SSL_SESSION *src)
269 {
270     return ssl_session_dup_intern(src, 1);
271 }
272 
273 /*
274  * Used internally when duplicating a session which might be already shared.
275  * We will have resumed the original session. Subsequently we might have marked
276  * it as non-resumable (e.g. in another thread) - but this copy should be ok to
277  * resume from.
278  */
ssl_session_dup(const SSL_SESSION * src,int ticket)279 SSL_SESSION *ssl_session_dup(const SSL_SESSION *src, int ticket)
280 {
281     SSL_SESSION *sess = ssl_session_dup_intern(src, ticket);
282 
283     if (sess != NULL)
284         sess->not_resumable = 0;
285 
286     return sess;
287 }
288 
SSL_SESSION_get_id(const SSL_SESSION * s,unsigned int * len)289 const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
290 {
291     if (len)
292         *len = (unsigned int)s->session_id_length;
293     return s->session_id;
294 }
295 
SSL_SESSION_get0_id_context(const SSL_SESSION * s,unsigned int * len)296 const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
297     unsigned int *len)
298 {
299     if (len != NULL)
300         *len = (unsigned int)s->sid_ctx_length;
301     return s->sid_ctx;
302 }
303 
SSL_SESSION_get_compress_id(const SSL_SESSION * s)304 unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
305 {
306     return s->compress_meth;
307 }
308 
309 /*
310  * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
311  * the ID with random junk repeatedly until we have no conflict is going to
312  * complete in one iteration pretty much "most" of the time (btw:
313  * understatement). So, if it takes us 10 iterations and we still can't avoid
314  * a conflict - well that's a reasonable point to call it quits. Either the
315  * RAND code is broken or someone is trying to open roughly very close to
316  * 2^256 SSL sessions to our server. How you might store that many sessions
317  * is perhaps a more interesting question ...
318  */
319 
320 #define MAX_SESS_ID_ATTEMPTS 10
def_generate_session_id(SSL * ssl,unsigned char * id,unsigned int * id_len)321 static int def_generate_session_id(SSL *ssl, unsigned char *id,
322     unsigned int *id_len)
323 {
324     unsigned int retry = 0;
325     do {
326         if (RAND_bytes_ex(ssl->ctx->libctx, id, *id_len, 0) <= 0)
327             return 0;
328 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
329         if (retry > 0) {
330             id[0]++;
331         }
332 #endif
333     } while (SSL_has_matching_session_id(ssl, id, *id_len) && (++retry < MAX_SESS_ID_ATTEMPTS));
334     if (retry < MAX_SESS_ID_ATTEMPTS)
335         return 1;
336     /* else - woops a session_id match */
337     /*
338      * XXX We should also check the external cache -- but the probability of
339      * a collision is negligible, and we could not prevent the concurrent
340      * creation of sessions with identical IDs since we currently don't have
341      * means to atomically check whether a session ID already exists and make
342      * a reservation for it if it does not (this problem applies to the
343      * internal cache as well).
344      */
345     return 0;
346 }
347 
ssl_generate_session_id(SSL_CONNECTION * s,SSL_SESSION * ss)348 int ssl_generate_session_id(SSL_CONNECTION *s, SSL_SESSION *ss)
349 {
350     unsigned int tmp;
351     GEN_SESSION_CB cb = def_generate_session_id;
352     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
353 
354     switch (s->version) {
355     case SSL3_VERSION:
356     case TLS1_VERSION:
357     case TLS1_1_VERSION:
358     case TLS1_2_VERSION:
359     case TLS1_3_VERSION:
360     case DTLS1_BAD_VER:
361     case DTLS1_VERSION:
362     case DTLS1_2_VERSION:
363         ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
364         break;
365     default:
366         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNSUPPORTED_SSL_VERSION);
367         return 0;
368     }
369 
370     /*-
371      * If RFC5077 ticket, use empty session ID (as server).
372      * Note that:
373      * (a) ssl_get_prev_session() does lookahead into the
374      *     ClientHello extensions to find the session ticket.
375      *     When ssl_get_prev_session() fails, statem_srvr.c calls
376      *     ssl_get_new_session() in tls_process_client_hello().
377      *     At that point, it has not yet parsed the extensions,
378      *     however, because of the lookahead, it already knows
379      *     whether a ticket is expected or not.
380      *
381      * (b) statem_clnt.c calls ssl_get_new_session() before parsing
382      *     ServerHello extensions, and before recording the session
383      *     ID received from the server, so this block is a noop.
384      */
385     if (s->ext.ticket_expected) {
386         ss->session_id_length = 0;
387         return 1;
388     }
389 
390     /* Choose which callback will set the session ID */
391     if (!CRYPTO_THREAD_read_lock(SSL_CONNECTION_GET_SSL(s)->lock))
392         return 0;
393     if (!CRYPTO_THREAD_read_lock(s->session_ctx->lock)) {
394         CRYPTO_THREAD_unlock(ssl->lock);
395         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
396             SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
397         return 0;
398     }
399     if (s->generate_session_id)
400         cb = s->generate_session_id;
401     else if (s->session_ctx->generate_session_id)
402         cb = s->session_ctx->generate_session_id;
403     CRYPTO_THREAD_unlock(s->session_ctx->lock);
404     CRYPTO_THREAD_unlock(ssl->lock);
405     /* Choose a session ID */
406     memset(ss->session_id, 0, ss->session_id_length);
407     tmp = (int)ss->session_id_length;
408     if (!cb(ssl, ss->session_id, &tmp)) {
409         /* The callback failed */
410         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
411             SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
412         return 0;
413     }
414     /*
415      * Don't allow the callback to set the session length to zero. nor
416      * set it higher than it was.
417      */
418     if (tmp == 0 || tmp > ss->session_id_length) {
419         /* The callback set an illegal length */
420         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
421             SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
422         return 0;
423     }
424     ss->session_id_length = tmp;
425     /* Finally, check for a conflict */
426     if (SSL_has_matching_session_id(ssl, ss->session_id,
427             (unsigned int)ss->session_id_length)) {
428         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SSL_SESSION_ID_CONFLICT);
429         return 0;
430     }
431 
432     return 1;
433 }
434 
ssl_get_new_session(SSL_CONNECTION * s,int session)435 int ssl_get_new_session(SSL_CONNECTION *s, int session)
436 {
437     /* This gets used by clients and servers. */
438 
439     SSL_SESSION *ss = NULL;
440 
441     if ((ss = SSL_SESSION_new()) == NULL) {
442         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
443         return 0;
444     }
445 
446     /* If the context has a default timeout, use it */
447     if (ossl_time_is_zero(s->session_ctx->session_timeout))
448         ss->timeout = SSL_CONNECTION_GET_SSL(s)->method->get_timeout();
449     else
450         ss->timeout = s->session_ctx->session_timeout;
451     ssl_session_calculate_timeout(ss);
452 
453     SSL_SESSION_free(s->session);
454     s->session = NULL;
455 
456     if (session) {
457         if (SSL_CONNECTION_IS_TLS13(s)) {
458             /*
459              * We generate the session id while constructing the
460              * NewSessionTicket in TLSv1.3.
461              */
462             ss->session_id_length = 0;
463         } else if (!ssl_generate_session_id(s, ss)) {
464             /* SSLfatal() already called */
465             SSL_SESSION_free(ss);
466             return 0;
467         }
468 
469     } else {
470         ss->session_id_length = 0;
471     }
472 
473     if (s->sid_ctx_length > sizeof(ss->sid_ctx)) {
474         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
475         SSL_SESSION_free(ss);
476         return 0;
477     }
478     memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
479     ss->sid_ctx_length = s->sid_ctx_length;
480     s->session = ss;
481     ss->ssl_version = s->version;
482     ss->verify_result = X509_V_OK;
483 
484     /* If client supports extended master secret set it in session */
485     if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
486         ss->flags |= SSL_SESS_FLAG_EXTMS;
487 
488     return 1;
489 }
490 
lookup_sess_in_cache(SSL_CONNECTION * s,const unsigned char * sess_id,size_t sess_id_len)491 SSL_SESSION *lookup_sess_in_cache(SSL_CONNECTION *s,
492     const unsigned char *sess_id,
493     size_t sess_id_len)
494 {
495     SSL_SESSION *ret = NULL;
496 
497     if ((s->session_ctx->session_cache_mode
498             & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)
499         == 0) {
500         SSL_SESSION data;
501 
502         data.ssl_version = s->version;
503         if (!ossl_assert(sess_id_len <= SSL_MAX_SSL_SESSION_ID_LENGTH))
504             return NULL;
505 
506         memcpy(data.session_id, sess_id, sess_id_len);
507         data.session_id_length = sess_id_len;
508 
509         if (!CRYPTO_THREAD_read_lock(s->session_ctx->lock))
510             return NULL;
511         ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
512         if (ret != NULL) {
513             /* don't allow other threads to steal it: */
514             if (!SSL_SESSION_up_ref(ret)) {
515                 CRYPTO_THREAD_unlock(s->session_ctx->lock);
516                 return NULL;
517             }
518         }
519         CRYPTO_THREAD_unlock(s->session_ctx->lock);
520         if (ret == NULL)
521             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);
522     }
523 
524     if (ret == NULL && s->session_ctx->get_session_cb != NULL) {
525         int copy = 1;
526 
527         ret = s->session_ctx->get_session_cb(SSL_CONNECTION_GET_USER_SSL(s),
528             sess_id, sess_id_len, &copy);
529 
530         if (ret != NULL) {
531             if (ret->not_resumable) {
532                 /* If its not resumable then ignore this session */
533                 if (!copy)
534                     SSL_SESSION_free(ret);
535                 return NULL;
536             }
537             ssl_tsan_counter(s->session_ctx,
538                 &s->session_ctx->stats.sess_cb_hit);
539 
540             /*
541              * Increment reference count now if the session callback asks us
542              * to do so (note that if the session structures returned by the
543              * callback are shared between threads, it must handle the
544              * reference count itself [i.e. copy == 0], or things won't be
545              * thread-safe).
546              */
547             if (copy && !SSL_SESSION_up_ref(ret))
548                 return NULL;
549 
550             /*
551              * Add the externally cached session to the internal cache as
552              * well if and only if we are supposed to.
553              */
554             if ((s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE) == 0) {
555                 /*
556                  * Either return value of SSL_CTX_add_session should not
557                  * interrupt the session resumption process. The return
558                  * value is intentionally ignored.
559                  */
560                 (void)SSL_CTX_add_session(s->session_ctx, ret);
561             }
562         }
563     }
564 
565     return ret;
566 }
567 
568 /*-
569  * ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
570  * connection. It is only called by servers.
571  *
572  *   hello: The parsed ClientHello data
573  *
574  * Returns:
575  *   -1: fatal error
576  *    0: no session found
577  *    1: a session may have been found.
578  *
579  * Side effects:
580  *   - If a session is found then s->session is pointed at it (after freeing an
581  *     existing session if need be) and s->verify_result is set from the session.
582  *   - Both for new and resumed sessions, s->ext.ticket_expected is set to 1
583  *     if the server should issue a new session ticket (to 0 otherwise).
584  */
ssl_get_prev_session(SSL_CONNECTION * s,CLIENTHELLO_MSG * hello)585 int ssl_get_prev_session(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello)
586 {
587     /* This is used only by servers. */
588 
589     SSL_SESSION *ret = NULL;
590     int fatal = 0;
591     int try_session_cache = 0;
592     SSL_TICKET_STATUS r;
593 
594     if (SSL_CONNECTION_IS_TLS13(s)) {
595         SSL_SESSION_free(s->session);
596         s->session = NULL;
597         /*
598          * By default we will send a new ticket. This can be overridden in the
599          * ticket processing.
600          */
601         s->ext.ticket_expected = 1;
602         if (!tls_parse_extension(s, TLSEXT_IDX_psk_kex_modes,
603                 SSL_EXT_CLIENT_HELLO, hello->pre_proc_exts,
604                 NULL, 0)
605             || !tls_parse_extension(s, TLSEXT_IDX_psk, SSL_EXT_CLIENT_HELLO,
606                 hello->pre_proc_exts, NULL, 0))
607             return -1;
608 
609         /* If we resumed, s->session will now be set */
610         ret = s->session;
611     } else {
612         /* sets s->ext.ticket_expected */
613         r = tls_get_ticket_from_client(s, hello, &ret);
614         switch (r) {
615         case SSL_TICKET_FATAL_ERR_MALLOC:
616         case SSL_TICKET_FATAL_ERR_OTHER:
617             fatal = 1;
618             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
619             goto err;
620         case SSL_TICKET_NONE:
621         case SSL_TICKET_EMPTY:
622             if (hello->session_id_len > 0) {
623                 try_session_cache = 1;
624                 ret = lookup_sess_in_cache(s, hello->session_id,
625                     hello->session_id_len);
626             }
627             break;
628         case SSL_TICKET_NO_DECRYPT:
629         case SSL_TICKET_SUCCESS:
630         case SSL_TICKET_SUCCESS_RENEW:
631             break;
632         }
633     }
634 
635     if (ret == NULL)
636         goto err;
637 
638     /* Now ret is non-NULL and we own one of its reference counts. */
639 
640     /* Check TLS version consistency */
641     if (ret->ssl_version != s->version)
642         goto err;
643 
644     if (ret->sid_ctx_length != s->sid_ctx_length
645         || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
646         /*
647          * We have the session requested by the client, but we don't want to
648          * use it in this context.
649          */
650         goto err; /* treat like cache miss */
651     }
652 
653     if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
654         /*
655          * We can't be sure if this session is being used out of context,
656          * which is especially important for SSL_VERIFY_PEER. The application
657          * should have used SSL[_CTX]_set_session_id_context. For this error
658          * case, we generate an error instead of treating the event like a
659          * cache miss (otherwise it would be easy for applications to
660          * effectively disable the session cache by accident without anyone
661          * noticing).
662          */
663 
664         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
665             SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
666         fatal = 1;
667         goto err;
668     }
669 
670     if (sess_timedout(ossl_time_now(), ret)) {
671         ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_timeout);
672         if (try_session_cache) {
673             /* session was from the cache, so remove it */
674             SSL_CTX_remove_session(s->session_ctx, ret);
675         }
676         goto err;
677     }
678 
679     /* Check extended master secret extension consistency */
680     if (ret->flags & SSL_SESS_FLAG_EXTMS) {
681         /* If old session includes extms, but new does not: abort handshake */
682         if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
683             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
684             fatal = 1;
685             goto err;
686         }
687     } else if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
688         /* If new session includes extms, but old does not: do not resume */
689         goto err;
690     }
691 
692     if (!SSL_CONNECTION_IS_TLS13(s)) {
693         /* We already did this for TLS1.3 */
694         SSL_SESSION_free(s->session);
695         s->session = ret;
696     }
697 
698     ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_hit);
699     s->verify_result = s->session->verify_result;
700     return 1;
701 
702 err:
703     if (ret != NULL) {
704         SSL_SESSION_free(ret);
705         /* In TLSv1.3 s->session was already set to ret, so we NULL it out */
706         if (SSL_CONNECTION_IS_TLS13(s))
707             s->session = NULL;
708 
709         if (!try_session_cache) {
710             /*
711              * The session was from a ticket, so we should issue a ticket for
712              * the new session
713              */
714             s->ext.ticket_expected = 1;
715         }
716     }
717     if (fatal)
718         return -1;
719 
720     return 0;
721 }
722 
SSL_CTX_add_session(SSL_CTX * ctx,SSL_SESSION * c)723 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
724 {
725     int ret = 0;
726     SSL_SESSION *s;
727 
728     /*
729      * add just 1 reference count for the SSL_CTX's session cache even though
730      * it has two ways of access: each session is in a doubly linked list and
731      * an lhash
732      */
733     if (!SSL_SESSION_up_ref(c))
734         return 0;
735     /*
736      * if session c is in already in cache, we take back the increment later
737      */
738 
739     if (!CRYPTO_THREAD_write_lock(ctx->lock)) {
740         SSL_SESSION_free(c);
741         return 0;
742     }
743     s = lh_SSL_SESSION_insert(ctx->sessions, c);
744 
745     /*
746      * s != NULL iff we already had a session with the given PID. In this
747      * case, s == c should hold (then we did not really modify
748      * ctx->sessions), or we're in trouble.
749      */
750     if (s != NULL && s != c) {
751         /* We *are* in trouble ... */
752         SSL_SESSION_list_remove(ctx, s);
753         SSL_SESSION_free(s);
754         /*
755          * ... so pretend the other session did not exist in cache (we cannot
756          * handle two SSL_SESSION structures with identical session ID in the
757          * same cache, which could happen e.g. when two threads concurrently
758          * obtain the same session from an external cache)
759          */
760         s = NULL;
761     } else if (s == NULL && lh_SSL_SESSION_retrieve(ctx->sessions, c) == NULL) {
762         /* s == NULL can also mean OOM error in lh_SSL_SESSION_insert ... */
763 
764         /*
765          * ... so take back the extra reference and also don't add
766          * the session to the SSL_SESSION_list at this time
767          */
768         s = c;
769     }
770 
771     /* Adjust last used time, and add back into the cache at the appropriate spot */
772     if (ctx->session_cache_mode & SSL_SESS_CACHE_UPDATE_TIME) {
773         c->time = ossl_time_now();
774         ssl_session_calculate_timeout(c);
775     }
776 
777     if (s == NULL) {
778         /*
779          * new cache entry -- remove old ones if cache has become too large
780          * delete cache entry *before* add, so we don't remove the one we're adding!
781          */
782 
783         ret = 1;
784 
785         if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
786             while (SSL_CTX_sess_number(ctx) >= SSL_CTX_sess_get_cache_size(ctx)) {
787                 if (!remove_session_lock(ctx, ctx->session_cache_tail, 0))
788                     break;
789                 else
790                     ssl_tsan_counter(ctx, &ctx->stats.sess_cache_full);
791             }
792         }
793     }
794 
795     SSL_SESSION_list_add(ctx, c);
796 
797     if (s != NULL) {
798         /*
799          * existing cache entry -- decrement previously incremented reference
800          * count because it already takes into account the cache
801          */
802 
803         SSL_SESSION_free(s); /* s == c */
804         ret = 0;
805     }
806     CRYPTO_THREAD_unlock(ctx->lock);
807     return ret;
808 }
809 
SSL_CTX_remove_session(SSL_CTX * ctx,SSL_SESSION * c)810 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
811 {
812     return remove_session_lock(ctx, c, 1);
813 }
814 
remove_session_lock(SSL_CTX * ctx,SSL_SESSION * c,int lck)815 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
816 {
817     SSL_SESSION *r;
818     int ret = 0;
819 
820     if ((c != NULL) && (c->session_id_length != 0)) {
821         if (lck) {
822             if (!CRYPTO_THREAD_write_lock(ctx->lock))
823                 return 0;
824         }
825         if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) != NULL) {
826             ret = 1;
827             r = lh_SSL_SESSION_delete(ctx->sessions, r);
828             SSL_SESSION_list_remove(ctx, r);
829         }
830         c->not_resumable = 1;
831 
832         if (lck)
833             CRYPTO_THREAD_unlock(ctx->lock);
834 
835         if (ctx->remove_session_cb != NULL)
836             ctx->remove_session_cb(ctx, c);
837 
838         if (ret)
839             SSL_SESSION_free(r);
840     }
841     return ret;
842 }
843 
SSL_SESSION_free(SSL_SESSION * ss)844 void SSL_SESSION_free(SSL_SESSION *ss)
845 {
846     int i;
847 
848     if (ss == NULL)
849         return;
850     CRYPTO_DOWN_REF(&ss->references, &i);
851     REF_PRINT_COUNT("SSL_SESSION", i, ss);
852     if (i > 0)
853         return;
854     REF_ASSERT_ISNT(i < 0);
855 
856     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
857 
858     OPENSSL_cleanse(ss->master_key, sizeof(ss->master_key));
859     OPENSSL_cleanse(ss->session_id, sizeof(ss->session_id));
860     X509_free(ss->peer);
861     EVP_PKEY_free(ss->peer_rpk);
862     OSSL_STACK_OF_X509_free(ss->peer_chain);
863     OPENSSL_free(ss->ext.hostname);
864     OPENSSL_free(ss->ext.tick);
865 #ifndef OPENSSL_NO_PSK
866     OPENSSL_free(ss->psk_identity_hint);
867     OPENSSL_free(ss->psk_identity);
868 #endif
869 #ifndef OPENSSL_NO_SRP
870     OPENSSL_free(ss->srp_username);
871 #endif
872     OPENSSL_free(ss->ext.alpn_selected);
873     OPENSSL_free(ss->ticket_appdata);
874     CRYPTO_FREE_REF(&ss->references);
875     OPENSSL_clear_free(ss, sizeof(*ss));
876 }
877 
SSL_SESSION_up_ref(SSL_SESSION * ss)878 int SSL_SESSION_up_ref(SSL_SESSION *ss)
879 {
880     int i;
881 
882     if (CRYPTO_UP_REF(&ss->references, &i) <= 0)
883         return 0;
884 
885     REF_PRINT_COUNT("SSL_SESSION", i, ss);
886     REF_ASSERT_ISNT(i < 2);
887     return ((i > 1) ? 1 : 0);
888 }
889 
SSL_set_session(SSL * s,SSL_SESSION * session)890 int SSL_set_session(SSL *s, SSL_SESSION *session)
891 {
892     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
893 
894     if (sc == NULL)
895         return 0;
896 
897     if (session != NULL && !SSL_SESSION_up_ref(session))
898         return 0;
899 
900     ssl_clear_bad_session(sc);
901     if (s->defltmeth != s->method) {
902         if (!SSL_set_ssl_method(s, s->defltmeth)) {
903             SSL_SESSION_free(session);
904             return 0;
905         }
906     }
907 
908     if (session != NULL)
909         sc->verify_result = session->verify_result;
910 
911     SSL_SESSION_free(sc->session);
912     sc->session = session;
913 
914     return 1;
915 }
916 
SSL_SESSION_set1_id(SSL_SESSION * s,const unsigned char * sid,unsigned int sid_len)917 int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
918     unsigned int sid_len)
919 {
920     if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
921         ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_TOO_LONG);
922         return 0;
923     }
924     s->session_id_length = sid_len;
925     if (sid != s->session_id && sid_len > 0)
926         memcpy(s->session_id, sid, sid_len);
927 
928     return 1;
929 }
930 
SSL_SESSION_set_timeout(SSL_SESSION * s,long t)931 long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
932 {
933     OSSL_TIME new_timeout = ossl_seconds2time(t);
934 
935     if (s == NULL || t < 0)
936         return 0;
937     if (s->owner != NULL) {
938         if (!CRYPTO_THREAD_write_lock(s->owner->lock))
939             return 0;
940         s->timeout = new_timeout;
941         ssl_session_calculate_timeout(s);
942         SSL_SESSION_list_add(s->owner, s);
943         CRYPTO_THREAD_unlock(s->owner->lock);
944     } else {
945         s->timeout = new_timeout;
946         ssl_session_calculate_timeout(s);
947     }
948     return 1;
949 }
950 
SSL_SESSION_get_timeout(const SSL_SESSION * s)951 long SSL_SESSION_get_timeout(const SSL_SESSION *s)
952 {
953     if (s == NULL)
954         return 0;
955     return (long)ossl_time_to_time_t(s->timeout);
956 }
957 
958 #ifndef OPENSSL_NO_DEPRECATED_3_4
SSL_SESSION_get_time(const SSL_SESSION * s)959 long SSL_SESSION_get_time(const SSL_SESSION *s)
960 {
961     return (long)SSL_SESSION_get_time_ex(s);
962 }
963 #endif
964 
SSL_SESSION_get_time_ex(const SSL_SESSION * s)965 time_t SSL_SESSION_get_time_ex(const SSL_SESSION *s)
966 {
967     if (s == NULL)
968         return 0;
969     return ossl_time_to_time_t(s->time);
970 }
971 
SSL_SESSION_set_time_ex(SSL_SESSION * s,time_t t)972 time_t SSL_SESSION_set_time_ex(SSL_SESSION *s, time_t t)
973 {
974     OSSL_TIME new_time = ossl_time_from_time_t(t);
975 
976     if (s == NULL)
977         return 0;
978     if (s->owner != NULL) {
979         if (!CRYPTO_THREAD_write_lock(s->owner->lock))
980             return 0;
981         s->time = new_time;
982         ssl_session_calculate_timeout(s);
983         SSL_SESSION_list_add(s->owner, s);
984         CRYPTO_THREAD_unlock(s->owner->lock);
985     } else {
986         s->time = new_time;
987         ssl_session_calculate_timeout(s);
988     }
989     return t;
990 }
991 
992 #ifndef OPENSSL_NO_DEPRECATED_3_4
SSL_SESSION_set_time(SSL_SESSION * s,long t)993 long SSL_SESSION_set_time(SSL_SESSION *s, long t)
994 {
995     return (long)SSL_SESSION_set_time_ex(s, (time_t)t);
996 }
997 #endif
998 
SSL_SESSION_get_protocol_version(const SSL_SESSION * s)999 int SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
1000 {
1001     return s->ssl_version;
1002 }
1003 
SSL_SESSION_set_protocol_version(SSL_SESSION * s,int version)1004 int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version)
1005 {
1006     s->ssl_version = version;
1007     return 1;
1008 }
1009 
SSL_SESSION_get0_cipher(const SSL_SESSION * s)1010 const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s)
1011 {
1012     return s->cipher;
1013 }
1014 
SSL_SESSION_set_cipher(SSL_SESSION * s,const SSL_CIPHER * cipher)1015 int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher)
1016 {
1017     s->cipher = cipher;
1018     return 1;
1019 }
1020 
SSL_SESSION_get0_hostname(const SSL_SESSION * s)1021 const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s)
1022 {
1023     return s->ext.hostname;
1024 }
1025 
SSL_SESSION_set1_hostname(SSL_SESSION * s,const char * hostname)1026 int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname)
1027 {
1028     OPENSSL_free(s->ext.hostname);
1029     if (hostname == NULL) {
1030         s->ext.hostname = NULL;
1031         return 1;
1032     }
1033     s->ext.hostname = OPENSSL_strdup(hostname);
1034 
1035     return s->ext.hostname != NULL;
1036 }
1037 
SSL_SESSION_has_ticket(const SSL_SESSION * s)1038 int SSL_SESSION_has_ticket(const SSL_SESSION *s)
1039 {
1040     return (s->ext.ticklen > 0) ? 1 : 0;
1041 }
1042 
SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION * s)1043 unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
1044 {
1045     return s->ext.tick_lifetime_hint;
1046 }
1047 
SSL_SESSION_get0_ticket(const SSL_SESSION * s,const unsigned char ** tick,size_t * len)1048 void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
1049     size_t *len)
1050 {
1051     *len = s->ext.ticklen;
1052     if (tick != NULL)
1053         *tick = s->ext.tick;
1054 }
1055 
SSL_SESSION_get_max_early_data(const SSL_SESSION * s)1056 uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s)
1057 {
1058     return s->ext.max_early_data;
1059 }
1060 
SSL_SESSION_set_max_early_data(SSL_SESSION * s,uint32_t max_early_data)1061 int SSL_SESSION_set_max_early_data(SSL_SESSION *s, uint32_t max_early_data)
1062 {
1063     s->ext.max_early_data = max_early_data;
1064 
1065     return 1;
1066 }
1067 
SSL_SESSION_get0_alpn_selected(const SSL_SESSION * s,const unsigned char ** alpn,size_t * len)1068 void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s,
1069     const unsigned char **alpn,
1070     size_t *len)
1071 {
1072     *alpn = s->ext.alpn_selected;
1073     *len = s->ext.alpn_selected_len;
1074 }
1075 
SSL_SESSION_set1_alpn_selected(SSL_SESSION * s,const unsigned char * alpn,size_t len)1076 int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s, const unsigned char *alpn,
1077     size_t len)
1078 {
1079     OPENSSL_free(s->ext.alpn_selected);
1080     if (alpn == NULL || len == 0) {
1081         s->ext.alpn_selected = NULL;
1082         s->ext.alpn_selected_len = 0;
1083         return 1;
1084     }
1085     s->ext.alpn_selected = OPENSSL_memdup(alpn, len);
1086     if (s->ext.alpn_selected == NULL) {
1087         s->ext.alpn_selected_len = 0;
1088         return 0;
1089     }
1090     s->ext.alpn_selected_len = len;
1091 
1092     return 1;
1093 }
1094 
SSL_SESSION_get0_peer(SSL_SESSION * s)1095 X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
1096 {
1097     return s->peer;
1098 }
1099 
SSL_SESSION_get0_peer_rpk(SSL_SESSION * s)1100 EVP_PKEY *SSL_SESSION_get0_peer_rpk(SSL_SESSION *s)
1101 {
1102     return s->peer_rpk;
1103 }
1104 
SSL_SESSION_set1_id_context(SSL_SESSION * s,const unsigned char * sid_ctx,unsigned int sid_ctx_len)1105 int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
1106     unsigned int sid_ctx_len)
1107 {
1108     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
1109         ERR_raise(ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
1110         return 0;
1111     }
1112     s->sid_ctx_length = sid_ctx_len;
1113     if (sid_ctx != s->sid_ctx)
1114         memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
1115 
1116     return 1;
1117 }
1118 
SSL_SESSION_is_resumable(const SSL_SESSION * s)1119 int SSL_SESSION_is_resumable(const SSL_SESSION *s)
1120 {
1121     /*
1122      * In the case of EAP-FAST, we can have a pre-shared "ticket" without a
1123      * session ID.
1124      */
1125     return !s->not_resumable
1126         && (s->session_id_length > 0 || s->ext.ticklen > 0);
1127 }
1128 
SSL_CTX_set_timeout(SSL_CTX * s,long t)1129 long SSL_CTX_set_timeout(SSL_CTX *s, long t)
1130 {
1131     long l;
1132 
1133     if (s == NULL)
1134         return 0;
1135     l = (long)ossl_time2seconds(s->session_timeout);
1136     s->session_timeout = ossl_seconds2time(t);
1137     return l;
1138 }
1139 
SSL_CTX_get_timeout(const SSL_CTX * s)1140 long SSL_CTX_get_timeout(const SSL_CTX *s)
1141 {
1142     if (s == NULL)
1143         return 0;
1144     return (long)ossl_time2seconds(s->session_timeout);
1145 }
1146 
SSL_set_session_secret_cb(SSL * s,tls_session_secret_cb_fn tls_session_secret_cb,void * arg)1147 int SSL_set_session_secret_cb(SSL *s,
1148     tls_session_secret_cb_fn tls_session_secret_cb,
1149     void *arg)
1150 {
1151     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
1152 
1153     if (sc == NULL)
1154         return 0;
1155 
1156     sc->ext.session_secret_cb = tls_session_secret_cb;
1157     sc->ext.session_secret_cb_arg = arg;
1158     return 1;
1159 }
1160 
SSL_set_session_ticket_ext_cb(SSL * s,tls_session_ticket_ext_cb_fn cb,void * arg)1161 int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
1162     void *arg)
1163 {
1164     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
1165 
1166     if (sc == NULL)
1167         return 0;
1168 
1169     sc->ext.session_ticket_cb = cb;
1170     sc->ext.session_ticket_cb_arg = arg;
1171     return 1;
1172 }
1173 
SSL_set_session_ticket_ext(SSL * s,void * ext_data,int ext_len)1174 int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
1175 {
1176     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
1177 
1178     if (sc == NULL)
1179         return 0;
1180 
1181     if (sc->version >= TLS1_VERSION) {
1182         OPENSSL_free(sc->ext.session_ticket);
1183         sc->ext.session_ticket = NULL;
1184         sc->ext.session_ticket = OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
1185         if (sc->ext.session_ticket == NULL)
1186             return 0;
1187 
1188         if (ext_data != NULL) {
1189             sc->ext.session_ticket->length = ext_len;
1190             sc->ext.session_ticket->data = sc->ext.session_ticket + 1;
1191             memcpy(sc->ext.session_ticket->data, ext_data, ext_len);
1192         } else {
1193             sc->ext.session_ticket->length = 0;
1194             sc->ext.session_ticket->data = NULL;
1195         }
1196 
1197         return 1;
1198     }
1199 
1200     return 0;
1201 }
1202 
1203 #ifndef OPENSSL_NO_DEPRECATED_3_4
SSL_CTX_flush_sessions(SSL_CTX * s,long t)1204 void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1205 {
1206     SSL_CTX_flush_sessions_ex(s, (time_t)t);
1207 }
1208 #endif
1209 
SSL_CTX_flush_sessions_ex(SSL_CTX * s,time_t t)1210 void SSL_CTX_flush_sessions_ex(SSL_CTX *s, time_t t)
1211 {
1212     STACK_OF(SSL_SESSION) *sk;
1213     SSL_SESSION *current;
1214     unsigned long i;
1215     const OSSL_TIME timeout = ossl_time_from_time_t(t);
1216 
1217     if (!CRYPTO_THREAD_write_lock(s->lock))
1218         return;
1219 
1220     sk = sk_SSL_SESSION_new_null();
1221     i = lh_SSL_SESSION_get_down_load(s->sessions);
1222     lh_SSL_SESSION_set_down_load(s->sessions, 0);
1223 
1224     /*
1225      * Iterate over the list from the back (oldest), and stop
1226      * when a session can no longer be removed.
1227      * Add the session to a temporary list to be freed outside
1228      * the SSL_CTX lock.
1229      * But still do the remove_session_cb() within the lock.
1230      */
1231     while (s->session_cache_tail != NULL) {
1232         current = s->session_cache_tail;
1233         if (t == 0 || sess_timedout(timeout, current)) {
1234             lh_SSL_SESSION_delete(s->sessions, current);
1235             SSL_SESSION_list_remove(s, current);
1236             current->not_resumable = 1;
1237             if (s->remove_session_cb != NULL)
1238                 s->remove_session_cb(s, current);
1239             /*
1240              * Throw the session on a stack, it's entirely plausible
1241              * that while freeing outside the critical section, the
1242              * session could be re-added, so avoid using the next/prev
1243              * pointers. If the stack failed to create, or the session
1244              * couldn't be put on the stack, just free it here
1245              */
1246             if (sk == NULL || !sk_SSL_SESSION_push(sk, current))
1247                 SSL_SESSION_free(current);
1248         } else {
1249             break;
1250         }
1251     }
1252 
1253     lh_SSL_SESSION_set_down_load(s->sessions, i);
1254     CRYPTO_THREAD_unlock(s->lock);
1255 
1256     sk_SSL_SESSION_pop_free(sk, SSL_SESSION_free);
1257 }
1258 
ssl_clear_bad_session(SSL_CONNECTION * s)1259 int ssl_clear_bad_session(SSL_CONNECTION *s)
1260 {
1261     if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) && !(SSL_in_init(SSL_CONNECTION_GET_SSL(s)) || SSL_in_before(SSL_CONNECTION_GET_SSL(s)))) {
1262         SSL_CTX_remove_session(s->session_ctx, s->session);
1263         return 1;
1264     } else
1265         return 0;
1266 }
1267 
1268 /* locked by SSL_CTX in the calling function */
SSL_SESSION_list_remove(SSL_CTX * ctx,SSL_SESSION * s)1269 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1270 {
1271     if ((s->next == NULL) || (s->prev == NULL))
1272         return;
1273 
1274     if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1275         /* last element in list */
1276         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1277             /* only one element in list */
1278             ctx->session_cache_head = NULL;
1279             ctx->session_cache_tail = NULL;
1280         } else {
1281             ctx->session_cache_tail = s->prev;
1282             s->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1283         }
1284     } else {
1285         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1286             /* first element in list */
1287             ctx->session_cache_head = s->next;
1288             s->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1289         } else {
1290             /* middle of list */
1291             s->next->prev = s->prev;
1292             s->prev->next = s->next;
1293         }
1294     }
1295     s->prev = s->next = NULL;
1296     s->owner = NULL;
1297 }
1298 
SSL_SESSION_list_add(SSL_CTX * ctx,SSL_SESSION * s)1299 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1300 {
1301     SSL_SESSION *next;
1302 
1303     if ((s->next != NULL) && (s->prev != NULL))
1304         SSL_SESSION_list_remove(ctx, s);
1305 
1306     if (ctx->session_cache_head == NULL) {
1307         ctx->session_cache_head = s;
1308         ctx->session_cache_tail = s;
1309         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1310         s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1311     } else {
1312         if (timeoutcmp(s, ctx->session_cache_head) >= 0) {
1313             /*
1314              * if we timeout after (or the same time as) the first
1315              * session, put us first - usual case
1316              */
1317             s->next = ctx->session_cache_head;
1318             s->next->prev = s;
1319             s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1320             ctx->session_cache_head = s;
1321         } else if (timeoutcmp(s, ctx->session_cache_tail) < 0) {
1322             /* if we timeout before the last session, put us last */
1323             s->prev = ctx->session_cache_tail;
1324             s->prev->next = s;
1325             s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1326             ctx->session_cache_tail = s;
1327         } else {
1328             /*
1329              * we timeout somewhere in-between - if there is only
1330              * one session in the cache it will be caught above
1331              */
1332             next = ctx->session_cache_head->next;
1333             while (next != (SSL_SESSION *)&(ctx->session_cache_tail)) {
1334                 if (timeoutcmp(s, next) >= 0) {
1335                     s->next = next;
1336                     s->prev = next->prev;
1337                     next->prev->next = s;
1338                     next->prev = s;
1339                     break;
1340                 }
1341                 next = next->next;
1342             }
1343         }
1344     }
1345     s->owner = ctx;
1346 }
1347 
SSL_CTX_sess_set_new_cb(SSL_CTX * ctx,int (* cb)(struct ssl_st * ssl,SSL_SESSION * sess))1348 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1349     int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess))
1350 {
1351     ctx->new_session_cb = cb;
1352 }
1353 
SSL_CTX_sess_get_new_cb(SSL_CTX * ctx)1354 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1355 {
1356     return ctx->new_session_cb;
1357 }
1358 
SSL_CTX_sess_set_remove_cb(SSL_CTX * ctx,void (* cb)(SSL_CTX * ctx,SSL_SESSION * sess))1359 void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1360     void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1361 {
1362     ctx->remove_session_cb = cb;
1363 }
1364 
SSL_CTX_sess_get_remove_cb(SSL_CTX * ctx)1365 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX *ctx,
1366     SSL_SESSION *sess)
1367 {
1368     return ctx->remove_session_cb;
1369 }
1370 
SSL_CTX_sess_set_get_cb(SSL_CTX * ctx,SSL_SESSION * (* cb)(SSL * ssl,const unsigned char * data,int len,int * copy))1371 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1372     SSL_SESSION *(*cb)(SSL *ssl,
1373         const unsigned char *data,
1374         int len, int *copy))
1375 {
1376     ctx->get_session_cb = cb;
1377 }
1378 
SSL_CTX_sess_get_get_cb(SSL_CTX * ctx)1379 SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl,
1380     const unsigned char
1381         *data,
1382     int len,
1383     int *copy)
1384 {
1385     return ctx->get_session_cb;
1386 }
1387 
SSL_CTX_set_info_callback(SSL_CTX * ctx,void (* cb)(const SSL * ssl,int type,int val))1388 void SSL_CTX_set_info_callback(SSL_CTX *ctx,
1389     void (*cb)(const SSL *ssl, int type, int val))
1390 {
1391     ctx->info_callback = cb;
1392 }
1393 
SSL_CTX_get_info_callback(SSL_CTX * ctx)1394 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type,
1395     int val)
1396 {
1397     return ctx->info_callback;
1398 }
1399 
SSL_CTX_set_client_cert_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey))1400 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1401     int (*cb)(SSL *ssl, X509 **x509,
1402         EVP_PKEY **pkey))
1403 {
1404     ctx->client_cert_cb = cb;
1405 }
1406 
SSL_CTX_get_client_cert_cb(SSL_CTX * ctx)1407 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509,
1408     EVP_PKEY **pkey)
1409 {
1410     return ctx->client_cert_cb;
1411 }
1412 
SSL_CTX_set_cookie_generate_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len))1413 void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1414     int (*cb)(SSL *ssl,
1415         unsigned char *cookie,
1416         unsigned int *cookie_len))
1417 {
1418     ctx->app_gen_cookie_cb = cb;
1419 }
1420 
SSL_CTX_set_cookie_verify_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,const unsigned char * cookie,unsigned int cookie_len))1421 void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1422     int (*cb)(SSL *ssl,
1423         const unsigned char *cookie,
1424         unsigned int cookie_len))
1425 {
1426     ctx->app_verify_cookie_cb = cb;
1427 }
1428 
SSL_SESSION_set1_ticket_appdata(SSL_SESSION * ss,const void * data,size_t len)1429 int SSL_SESSION_set1_ticket_appdata(SSL_SESSION *ss, const void *data, size_t len)
1430 {
1431     OPENSSL_free(ss->ticket_appdata);
1432     ss->ticket_appdata_len = 0;
1433     if (data == NULL || len == 0) {
1434         ss->ticket_appdata = NULL;
1435         return 1;
1436     }
1437     ss->ticket_appdata = OPENSSL_memdup(data, len);
1438     if (ss->ticket_appdata != NULL) {
1439         ss->ticket_appdata_len = len;
1440         return 1;
1441     }
1442     return 0;
1443 }
1444 
SSL_SESSION_get0_ticket_appdata(SSL_SESSION * ss,void ** data,size_t * len)1445 int SSL_SESSION_get0_ticket_appdata(SSL_SESSION *ss, void **data, size_t *len)
1446 {
1447     *data = ss->ticket_appdata;
1448     *len = ss->ticket_appdata_len;
1449     return 1;
1450 }
1451 
SSL_CTX_set_stateless_cookie_generate_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,unsigned char * cookie,size_t * cookie_len))1452 void SSL_CTX_set_stateless_cookie_generate_cb(
1453     SSL_CTX *ctx,
1454     int (*cb)(SSL *ssl,
1455         unsigned char *cookie,
1456         size_t *cookie_len))
1457 {
1458     ctx->gen_stateless_cookie_cb = cb;
1459 }
1460 
SSL_CTX_set_stateless_cookie_verify_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,const unsigned char * cookie,size_t cookie_len))1461 void SSL_CTX_set_stateless_cookie_verify_cb(
1462     SSL_CTX *ctx,
1463     int (*cb)(SSL *ssl,
1464         const unsigned char *cookie,
1465         size_t cookie_len))
1466 {
1467     ctx->verify_stateless_cookie_cb = cb;
1468 }
1469 
1470 IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)
1471