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