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