Add support for SSL_SESSION_is_resumable()
[openssl.git] / ssl / ssl_sess.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2005 Nokia. All rights reserved.
12  *
13  * The portions of the attached software ("Contribution") is developed by
14  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
15  * license.
16  *
17  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
18  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
19  * support (see RFC 4279) to OpenSSL.
20  *
21  * No patent licenses or other rights except those expressly stated in
22  * the OpenSSL open source license shall be deemed granted or received
23  * expressly, by implication, estoppel, or otherwise.
24  *
25  * No assurances are provided by Nokia that the Contribution does not
26  * infringe the patent or other intellectual property rights of any third
27  * party or that the license provides you with all the necessary rights
28  * to make use of the Contribution.
29  *
30  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
31  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
32  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
33  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
34  * OTHERWISE.
35  */
36
37 #include <stdio.h>
38 #include <openssl/lhash.h>
39 #include <openssl/rand.h>
40 #include <openssl/engine.h>
41 #include "ssl_locl.h"
42 #include "statem/statem_locl.h"
43
44 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
45 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
46 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
47
48 /*
49  * SSL_get_session() and SSL_get1_session() are problematic in TLS1.3 because,
50  * unlike in earlier protocol versions, the session ticket may not have been
51  * sent yet even though a handshake has finished. The session ticket data could
52  * come in sometime later...or even change if multiple session ticket messages
53  * are sent from the server. The preferred way for applications to obtain
54  * a resumable session is to use SSL_CTX_sess_set_new_cb().
55  */
56
57 SSL_SESSION *SSL_get_session(const SSL *ssl)
58 /* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
59 {
60     return (ssl->session);
61 }
62
63 SSL_SESSION *SSL_get1_session(SSL *ssl)
64 /* variant of SSL_get_session: caller really gets something */
65 {
66     SSL_SESSION *sess;
67     /*
68      * Need to lock this all up rather than just use CRYPTO_add so that
69      * somebody doesn't free ssl->session between when we check it's non-null
70      * and when we up the reference count.
71      */
72     CRYPTO_THREAD_read_lock(ssl->lock);
73     sess = ssl->session;
74     if (sess)
75         SSL_SESSION_up_ref(sess);
76     CRYPTO_THREAD_unlock(ssl->lock);
77     return sess;
78 }
79
80 int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
81 {
82     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
83 }
84
85 void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
86 {
87     return (CRYPTO_get_ex_data(&s->ex_data, idx));
88 }
89
90 SSL_SESSION *SSL_SESSION_new(void)
91 {
92     SSL_SESSION *ss;
93
94     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
95         return NULL;
96
97     ss = OPENSSL_zalloc(sizeof(*ss));
98     if (ss == NULL) {
99         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
100         return NULL;
101     }
102
103     ss->verify_result = 1;      /* avoid 0 (= X509_V_OK) just in case */
104     ss->references = 1;
105     ss->timeout = 60 * 5 + 4;   /* 5 minute timeout by default */
106     ss->time = (unsigned long)time(NULL);
107     ss->lock = CRYPTO_THREAD_lock_new();
108     if (ss->lock == NULL) {
109         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
110         OPENSSL_free(ss);
111         return NULL;
112     }
113
114     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data)) {
115         CRYPTO_THREAD_lock_free(ss->lock);
116         OPENSSL_free(ss);
117         return NULL;
118     }
119     return ss;
120 }
121
122 /*
123  * Create a new SSL_SESSION and duplicate the contents of |src| into it. If
124  * ticket == 0 then no ticket information is duplicated, otherwise it is.
125  */
126 SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)
127 {
128     SSL_SESSION *dest;
129
130     dest = OPENSSL_malloc(sizeof(*src));
131     if (dest == NULL) {
132         goto err;
133     }
134     memcpy(dest, src, sizeof(*dest));
135
136     /*
137      * Set the various pointers to NULL so that we can call SSL_SESSION_free in
138      * the case of an error whilst halfway through constructing dest
139      */
140 #ifndef OPENSSL_NO_PSK
141     dest->psk_identity_hint = NULL;
142     dest->psk_identity = NULL;
143 #endif
144     dest->ciphers = NULL;
145     dest->ext.hostname = NULL;
146 #ifndef OPENSSL_NO_EC
147     dest->ext.ecpointformats = NULL;
148     dest->ext.supportedgroups = NULL;
149 #endif
150     dest->ext.tick = NULL;
151 #ifndef OPENSSL_NO_SRP
152     dest->srp_username = NULL;
153 #endif
154     memset(&dest->ex_data, 0, sizeof(dest->ex_data));
155
156     /* We deliberately don't copy the prev and next pointers */
157     dest->prev = NULL;
158     dest->next = NULL;
159
160     dest->references = 1;
161
162     dest->lock = CRYPTO_THREAD_lock_new();
163     if (dest->lock == NULL)
164         goto err;
165
166     if (src->peer != NULL)
167         X509_up_ref(src->peer);
168
169     if (src->peer_chain != NULL) {
170         dest->peer_chain = X509_chain_up_ref(src->peer_chain);
171         if (dest->peer_chain == NULL)
172             goto err;
173     }
174 #ifndef OPENSSL_NO_PSK
175     if (src->psk_identity_hint) {
176         dest->psk_identity_hint = OPENSSL_strdup(src->psk_identity_hint);
177         if (dest->psk_identity_hint == NULL) {
178             goto err;
179         }
180     }
181     if (src->psk_identity) {
182         dest->psk_identity = OPENSSL_strdup(src->psk_identity);
183         if (dest->psk_identity == NULL) {
184             goto err;
185         }
186     }
187 #endif
188
189     if (src->ciphers != NULL) {
190         dest->ciphers = sk_SSL_CIPHER_dup(src->ciphers);
191         if (dest->ciphers == NULL)
192             goto err;
193     }
194
195     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
196                             &dest->ex_data, &src->ex_data)) {
197         goto err;
198     }
199
200     if (src->ext.hostname) {
201         dest->ext.hostname = OPENSSL_strdup(src->ext.hostname);
202         if (dest->ext.hostname == NULL) {
203             goto err;
204         }
205     }
206 #ifndef OPENSSL_NO_EC
207     if (src->ext.ecpointformats) {
208         dest->ext.ecpointformats =
209             OPENSSL_memdup(src->ext.ecpointformats,
210                            src->ext.ecpointformats_len);
211         if (dest->ext.ecpointformats == NULL)
212             goto err;
213     }
214     if (src->ext.supportedgroups) {
215         dest->ext.supportedgroups =
216             OPENSSL_memdup(src->ext.supportedgroups,
217                            src->ext.supportedgroups_len);
218         if (dest->ext.supportedgroups == NULL)
219             goto err;
220     }
221 #endif
222
223     if (ticket != 0) {
224         dest->ext.tick =
225             OPENSSL_memdup(src->ext.tick, src->ext.ticklen);
226         if (dest->ext.tick == NULL)
227             goto err;
228     } else {
229         dest->ext.tick_lifetime_hint = 0;
230         dest->ext.ticklen = 0;
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                  * The following should not return 1, otherwise, things are
549                  * very strange
550                  */
551                 if (SSL_CTX_add_session(s->session_ctx, ret))
552                     goto err;
553             }
554         }
555     }
556
557     if (ret == NULL)
558         goto err;
559
560     /* Now ret is non-NULL and we own one of its reference counts. */
561
562     /* Check TLS version consistency */
563     if (ret->ssl_version != s->version)
564         goto err;
565
566     if (ret->sid_ctx_length != s->sid_ctx_length
567         || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
568         /*
569          * We have the session requested by the client, but we don't want to
570          * use it in this context.
571          */
572         goto err;               /* treat like cache miss */
573     }
574
575     if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
576         /*
577          * We can't be sure if this session is being used out of context,
578          * which is especially important for SSL_VERIFY_PEER. The application
579          * should have used SSL[_CTX]_set_session_id_context. For this error
580          * case, we generate an error instead of treating the event like a
581          * cache miss (otherwise it would be easy for applications to
582          * effectively disable the session cache by accident without anyone
583          * noticing).
584          */
585
586         SSLerr(SSL_F_SSL_GET_PREV_SESSION,
587                SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
588         fatal = 1;
589         goto err;
590     }
591
592     if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
593         s->session_ctx->stats.sess_timeout++;
594         if (try_session_cache) {
595             /* session was from the cache, so remove it */
596             SSL_CTX_remove_session(s->session_ctx, ret);
597         }
598         goto err;
599     }
600
601     /* Check extended master secret extension consistency */
602     if (ret->flags & SSL_SESS_FLAG_EXTMS) {
603         /* If old session includes extms, but new does not: abort handshake */
604         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
605             SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_INCONSISTENT_EXTMS);
606             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
607             fatal = 1;
608             goto err;
609         }
610     } else if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {
611         /* If new session includes extms, but old does not: do not resume */
612         goto err;
613     }
614
615     if (!SSL_IS_TLS13(s)) {
616         /* We already did this for TLS1.3 */
617         SSL_SESSION_free(s->session);
618         s->session = ret;
619     }
620
621     s->session_ctx->stats.sess_hit++;
622     s->verify_result = s->session->verify_result;
623     return 1;
624
625  err:
626     if (ret != NULL) {
627         SSL_SESSION_free(ret);
628         /* In TLSv1.3 s->session was already set to ret, so we NULL it out */
629         if (SSL_IS_TLS13(s))
630             s->session = NULL;
631
632         if (!try_session_cache) {
633             /*
634              * The session was from a ticket, so we should issue a ticket for
635              * the new session
636              */
637             s->ext.ticket_expected = 1;
638         }
639     }
640     if (fatal) {
641         *al = SSL_AD_INTERNAL_ERROR;
642         return -1;
643     }
644
645     return 0;
646 }
647
648 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
649 {
650     int ret = 0;
651     SSL_SESSION *s;
652
653     /*
654      * add just 1 reference count for the SSL_CTX's session cache even though
655      * it has two ways of access: each session is in a doubly linked list and
656      * an lhash
657      */
658     SSL_SESSION_up_ref(c);
659     /*
660      * if session c is in already in cache, we take back the increment later
661      */
662
663     CRYPTO_THREAD_write_lock(ctx->lock);
664     s = lh_SSL_SESSION_insert(ctx->sessions, c);
665
666     /*
667      * s != NULL iff we already had a session with the given PID. In this
668      * case, s == c should hold (then we did not really modify
669      * ctx->sessions), or we're in trouble.
670      */
671     if (s != NULL && s != c) {
672         /* We *are* in trouble ... */
673         SSL_SESSION_list_remove(ctx, s);
674         SSL_SESSION_free(s);
675         /*
676          * ... so pretend the other session did not exist in cache (we cannot
677          * handle two SSL_SESSION structures with identical session ID in the
678          * same cache, which could happen e.g. when two threads concurrently
679          * obtain the same session from an external cache)
680          */
681         s = NULL;
682     } else if (s == NULL &&
683                lh_SSL_SESSION_retrieve(ctx->sessions, c) == NULL) {
684         /* s == NULL can also mean OOM error in lh_SSL_SESSION_insert ... */
685
686         /*
687          * ... so take back the extra reference and also don't add
688          * the session to the SSL_SESSION_list at this time
689          */
690         s = c;
691     }
692
693     /* Put at the head of the queue unless it is already in the cache */
694     if (s == NULL)
695         SSL_SESSION_list_add(ctx, c);
696
697     if (s != NULL) {
698         /*
699          * existing cache entry -- decrement previously incremented reference
700          * count because it already takes into account the cache
701          */
702
703         SSL_SESSION_free(s);    /* s == c */
704         ret = 0;
705     } else {
706         /*
707          * new cache entry -- remove old ones if cache has become too large
708          */
709
710         ret = 1;
711
712         if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
713             while (SSL_CTX_sess_number(ctx) > SSL_CTX_sess_get_cache_size(ctx)) {
714                 if (!remove_session_lock(ctx, ctx->session_cache_tail, 0))
715                     break;
716                 else
717                     ctx->stats.sess_cache_full++;
718             }
719         }
720     }
721     CRYPTO_THREAD_unlock(ctx->lock);
722     return ret;
723 }
724
725 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
726 {
727     return remove_session_lock(ctx, c, 1);
728 }
729
730 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
731 {
732     SSL_SESSION *r;
733     int ret = 0;
734
735     if ((c != NULL) && (c->session_id_length != 0)) {
736         if (lck)
737             CRYPTO_THREAD_write_lock(ctx->lock);
738         if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
739             ret = 1;
740             r = lh_SSL_SESSION_delete(ctx->sessions, c);
741             SSL_SESSION_list_remove(ctx, c);
742         }
743         c->not_resumable = 1;
744
745         if (lck)
746             CRYPTO_THREAD_unlock(ctx->lock);
747
748         if (ret)
749             SSL_SESSION_free(r);
750
751         if (ctx->remove_session_cb != NULL)
752             ctx->remove_session_cb(ctx, c);
753     } else
754         ret = 0;
755     return (ret);
756 }
757
758 void SSL_SESSION_free(SSL_SESSION *ss)
759 {
760     int i;
761
762     if (ss == NULL)
763         return;
764
765     CRYPTO_DOWN_REF(&ss->references, &i, ss->lock);
766     REF_PRINT_COUNT("SSL_SESSION", ss);
767     if (i > 0)
768         return;
769     REF_ASSERT_ISNT(i < 0);
770
771     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
772
773     OPENSSL_cleanse(ss->master_key, sizeof ss->master_key);
774     OPENSSL_cleanse(ss->session_id, sizeof ss->session_id);
775     X509_free(ss->peer);
776     sk_X509_pop_free(ss->peer_chain, X509_free);
777     sk_SSL_CIPHER_free(ss->ciphers);
778     OPENSSL_free(ss->ext.hostname);
779     OPENSSL_free(ss->ext.tick);
780 #ifndef OPENSSL_NO_EC
781     OPENSSL_free(ss->ext.ecpointformats);
782     ss->ext.ecpointformats = NULL;
783     ss->ext.ecpointformats_len = 0;
784     OPENSSL_free(ss->ext.supportedgroups);
785     ss->ext.supportedgroups = NULL;
786     ss->ext.supportedgroups_len = 0;
787 #endif                          /* OPENSSL_NO_EC */
788 #ifndef OPENSSL_NO_PSK
789     OPENSSL_free(ss->psk_identity_hint);
790     OPENSSL_free(ss->psk_identity);
791 #endif
792 #ifndef OPENSSL_NO_SRP
793     OPENSSL_free(ss->srp_username);
794 #endif
795     OPENSSL_free(ss->ext.alpn_selected);
796     CRYPTO_THREAD_lock_free(ss->lock);
797     OPENSSL_clear_free(ss, sizeof(*ss));
798 }
799
800 int SSL_SESSION_up_ref(SSL_SESSION *ss)
801 {
802     int i;
803
804     if (CRYPTO_UP_REF(&ss->references, &i, ss->lock) <= 0)
805         return 0;
806
807     REF_PRINT_COUNT("SSL_SESSION", ss);
808     REF_ASSERT_ISNT(i < 2);
809     return ((i > 1) ? 1 : 0);
810 }
811
812 int SSL_set_session(SSL *s, SSL_SESSION *session)
813 {
814     ssl_clear_bad_session(s);
815     if (s->ctx->method != s->method) {
816         if (!SSL_set_ssl_method(s, s->ctx->method))
817             return 0;
818     }
819
820     if (session != NULL) {
821         SSL_SESSION_up_ref(session);
822         s->verify_result = session->verify_result;
823     }
824     SSL_SESSION_free(s->session);
825     s->session = session;
826
827     return 1;
828 }
829
830 int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
831                         unsigned int sid_len)
832 {
833     if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
834       SSLerr(SSL_F_SSL_SESSION_SET1_ID,
835              SSL_R_SSL_SESSION_ID_TOO_LONG);
836       return 0;
837     }
838     s->session_id_length = sid_len;
839     if (sid != s->session_id)
840         memcpy(s->session_id, sid, sid_len);
841     return 1;
842 }
843
844 long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
845 {
846     if (s == NULL)
847         return (0);
848     s->timeout = t;
849     return (1);
850 }
851
852 long SSL_SESSION_get_timeout(const SSL_SESSION *s)
853 {
854     if (s == NULL)
855         return (0);
856     return (s->timeout);
857 }
858
859 long SSL_SESSION_get_time(const SSL_SESSION *s)
860 {
861     if (s == NULL)
862         return (0);
863     return (s->time);
864 }
865
866 long SSL_SESSION_set_time(SSL_SESSION *s, long t)
867 {
868     if (s == NULL)
869         return (0);
870     s->time = t;
871     return (t);
872 }
873
874 int SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
875 {
876     return s->ssl_version;
877 }
878
879 const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s)
880 {
881     return s->cipher;
882 }
883
884 const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s)
885 {
886     return s->ext.hostname;
887 }
888
889 int SSL_SESSION_has_ticket(const SSL_SESSION *s)
890 {
891     return (s->ext.ticklen > 0) ? 1 : 0;
892 }
893
894 unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
895 {
896     return s->ext.tick_lifetime_hint;
897 }
898
899 void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
900                              size_t *len)
901 {
902     *len = s->ext.ticklen;
903     if (tick != NULL)
904         *tick = s->ext.tick;
905 }
906
907 uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s)
908 {
909     return s->ext.max_early_data;
910 }
911
912 X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
913 {
914     return s->peer;
915 }
916
917 int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
918                                 unsigned int sid_ctx_len)
919 {
920     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
921         SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
922                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
923         return 0;
924     }
925     s->sid_ctx_length = sid_ctx_len;
926     if (sid_ctx != s->sid_ctx)
927         memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
928
929     return 1;
930 }
931
932 int SSL_SESSION_is_resumable(const SSL_SESSION *s)
933 {
934     /*
935      * In the case of EAP-FAST, we can have a pre-shared "ticket" without a
936      * session ID.
937      */
938     return !s->not_resumable
939            && (s->session_id_length > 0 || s->ext.ticklen > 0);
940 }
941
942 long SSL_CTX_set_timeout(SSL_CTX *s, long t)
943 {
944     long l;
945     if (s == NULL)
946         return (0);
947     l = s->session_timeout;
948     s->session_timeout = t;
949     return (l);
950 }
951
952 long SSL_CTX_get_timeout(const SSL_CTX *s)
953 {
954     if (s == NULL)
955         return (0);
956     return (s->session_timeout);
957 }
958
959 int SSL_set_session_secret_cb(SSL *s,
960                               tls_session_secret_cb_fn tls_session_secret_cb,
961                               void *arg)
962 {
963     if (s == NULL)
964         return (0);
965     s->ext.session_secret_cb = tls_session_secret_cb;
966     s->ext.session_secret_cb_arg = arg;
967     return (1);
968 }
969
970 int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
971                                   void *arg)
972 {
973     if (s == NULL)
974         return (0);
975     s->ext.session_ticket_cb = cb;
976     s->ext.session_ticket_cb_arg = arg;
977     return (1);
978 }
979
980 int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
981 {
982     if (s->version >= TLS1_VERSION) {
983         OPENSSL_free(s->ext.session_ticket);
984         s->ext.session_ticket = NULL;
985         s->ext.session_ticket =
986             OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
987         if (s->ext.session_ticket == NULL) {
988             SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE);
989             return 0;
990         }
991
992         if (ext_data != NULL) {
993             s->ext.session_ticket->length = ext_len;
994             s->ext.session_ticket->data = s->ext.session_ticket + 1;
995             memcpy(s->ext.session_ticket->data, ext_data, ext_len);
996         } else {
997             s->ext.session_ticket->length = 0;
998             s->ext.session_ticket->data = NULL;
999         }
1000
1001         return 1;
1002     }
1003
1004     return 0;
1005 }
1006
1007 typedef struct timeout_param_st {
1008     SSL_CTX *ctx;
1009     long time;
1010     LHASH_OF(SSL_SESSION) *cache;
1011 } TIMEOUT_PARAM;
1012
1013 static void timeout_cb(SSL_SESSION *s, TIMEOUT_PARAM *p)
1014 {
1015     if ((p->time == 0) || (p->time > (s->time + s->timeout))) { /* timeout */
1016         /*
1017          * The reason we don't call SSL_CTX_remove_session() is to save on
1018          * locking overhead
1019          */
1020         (void)lh_SSL_SESSION_delete(p->cache, s);
1021         SSL_SESSION_list_remove(p->ctx, s);
1022         s->not_resumable = 1;
1023         if (p->ctx->remove_session_cb != NULL)
1024             p->ctx->remove_session_cb(p->ctx, s);
1025         SSL_SESSION_free(s);
1026     }
1027 }
1028
1029 IMPLEMENT_LHASH_DOALL_ARG(SSL_SESSION, TIMEOUT_PARAM);
1030
1031 void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1032 {
1033     unsigned long i;
1034     TIMEOUT_PARAM tp;
1035
1036     tp.ctx = s;
1037     tp.cache = s->sessions;
1038     if (tp.cache == NULL)
1039         return;
1040     tp.time = t;
1041     CRYPTO_THREAD_write_lock(s->lock);
1042     i = lh_SSL_SESSION_get_down_load(s->sessions);
1043     lh_SSL_SESSION_set_down_load(s->sessions, 0);
1044     lh_SSL_SESSION_doall_TIMEOUT_PARAM(tp.cache, timeout_cb, &tp);
1045     lh_SSL_SESSION_set_down_load(s->sessions, i);
1046     CRYPTO_THREAD_unlock(s->lock);
1047 }
1048
1049 int ssl_clear_bad_session(SSL *s)
1050 {
1051     if ((s->session != NULL) &&
1052         !(s->shutdown & SSL_SENT_SHUTDOWN) &&
1053         !(SSL_in_init(s) || SSL_in_before(s))) {
1054         SSL_CTX_remove_session(s->session_ctx, s->session);
1055         return (1);
1056     } else
1057         return (0);
1058 }
1059
1060 /* locked by SSL_CTX in the calling function */
1061 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1062 {
1063     if ((s->next == NULL) || (s->prev == NULL))
1064         return;
1065
1066     if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1067         /* last element in list */
1068         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1069             /* only one element in list */
1070             ctx->session_cache_head = NULL;
1071             ctx->session_cache_tail = NULL;
1072         } else {
1073             ctx->session_cache_tail = s->prev;
1074             s->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1075         }
1076     } else {
1077         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1078             /* first element in list */
1079             ctx->session_cache_head = s->next;
1080             s->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1081         } else {
1082             /* middle of list */
1083             s->next->prev = s->prev;
1084             s->prev->next = s->next;
1085         }
1086     }
1087     s->prev = s->next = NULL;
1088 }
1089
1090 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1091 {
1092     if ((s->next != NULL) && (s->prev != NULL))
1093         SSL_SESSION_list_remove(ctx, s);
1094
1095     if (ctx->session_cache_head == NULL) {
1096         ctx->session_cache_head = s;
1097         ctx->session_cache_tail = s;
1098         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1099         s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1100     } else {
1101         s->next = ctx->session_cache_head;
1102         s->next->prev = s;
1103         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1104         ctx->session_cache_head = s;
1105     }
1106 }
1107
1108 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1109                              int (*cb) (struct ssl_st *ssl, SSL_SESSION *sess))
1110 {
1111     ctx->new_session_cb = cb;
1112 }
1113
1114 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (SSL *ssl, SSL_SESSION *sess) {
1115     return ctx->new_session_cb;
1116 }
1117
1118 void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1119                                 void (*cb) (SSL_CTX *ctx, SSL_SESSION *sess))
1120 {
1121     ctx->remove_session_cb = cb;
1122 }
1123
1124 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (SSL_CTX *ctx,
1125                                                   SSL_SESSION *sess) {
1126     return ctx->remove_session_cb;
1127 }
1128
1129 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1130                              SSL_SESSION *(*cb) (struct ssl_st *ssl,
1131                                                  const unsigned char *data,
1132                                                  int len, int *copy))
1133 {
1134     ctx->get_session_cb = cb;
1135 }
1136
1137 SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (SSL *ssl,
1138                                                        const unsigned char
1139                                                        *data, int len,
1140                                                        int *copy) {
1141     return ctx->get_session_cb;
1142 }
1143
1144 void SSL_CTX_set_info_callback(SSL_CTX *ctx,
1145                                void (*cb) (const SSL *ssl, int type, int val))
1146 {
1147     ctx->info_callback = cb;
1148 }
1149
1150 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
1151                                                  int val) {
1152     return ctx->info_callback;
1153 }
1154
1155 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1156                                 int (*cb) (SSL *ssl, X509 **x509,
1157                                            EVP_PKEY **pkey))
1158 {
1159     ctx->client_cert_cb = cb;
1160 }
1161
1162 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
1163                                                  EVP_PKEY **pkey) {
1164     return ctx->client_cert_cb;
1165 }
1166
1167 #ifndef OPENSSL_NO_ENGINE
1168 int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1169 {
1170     if (!ENGINE_init(e)) {
1171         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, ERR_R_ENGINE_LIB);
1172         return 0;
1173     }
1174     if (!ENGINE_get_ssl_client_cert_function(e)) {
1175         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1176                SSL_R_NO_CLIENT_CERT_METHOD);
1177         ENGINE_finish(e);
1178         return 0;
1179     }
1180     ctx->client_cert_engine = e;
1181     return 1;
1182 }
1183 #endif
1184
1185 void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1186                                     int (*cb) (SSL *ssl,
1187                                                unsigned char *cookie,
1188                                                unsigned int *cookie_len))
1189 {
1190     ctx->app_gen_cookie_cb = cb;
1191 }
1192
1193 void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1194                                   int (*cb) (SSL *ssl,
1195                                              const unsigned char *cookie,
1196                                              unsigned int cookie_len))
1197 {
1198     ctx->app_verify_cookie_cb = cb;
1199 }
1200
1201 IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)