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