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