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