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