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