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