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