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