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