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