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