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