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