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