3b9a9f75359e59b77a1179b26dccc3500673a404
[openssl.git] / ssl / ssl_sess.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2005 Nokia. All rights reserved.
112  *
113  * The portions of the attached software ("Contribution") is developed by
114  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
115  * license.
116  *
117  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
118  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
119  * support (see RFC 4279) to OpenSSL.
120  *
121  * No patent licenses or other rights except those expressly stated in
122  * the OpenSSL open source license shall be deemed granted or received
123  * expressly, by implication, estoppel, or otherwise.
124  *
125  * No assurances are provided by Nokia that the Contribution does not
126  * infringe the patent or other intellectual property rights of any third
127  * party or that the license provides you with all the necessary rights
128  * to make use of the Contribution.
129  *
130  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
131  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
132  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
133  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
134  * OTHERWISE.
135  */
136
137 #include <stdio.h>
138 #include <openssl/lhash.h>
139 #include <openssl/rand.h>
140 #include <openssl/engine.h>
141 #include "ssl_locl.h"
142
143 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
144 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
145 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
146
147 SSL_SESSION *SSL_get_session(const SSL *ssl)
148 /* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
149 {
150     return (ssl->session);
151 }
152
153 SSL_SESSION *SSL_get1_session(SSL *ssl)
154 /* variant of SSL_get_session: caller really gets something */
155 {
156     SSL_SESSION *sess;
157     /*
158      * Need to lock this all up rather than just use CRYPTO_add so that
159      * somebody doesn't free ssl->session between when we check it's non-null
160      * and when we up the reference count.
161      */
162     CRYPTO_THREAD_read_lock(ssl->lock);
163     sess = ssl->session;
164     if (sess)
165         SSL_SESSION_up_ref(sess);
166     CRYPTO_THREAD_unlock(ssl->lock);
167     return sess;
168 }
169
170 int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
171 {
172     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
173 }
174
175 void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
176 {
177     return (CRYPTO_get_ex_data(&s->ex_data, idx));
178 }
179
180 SSL_SESSION *SSL_SESSION_new(void)
181 {
182     SSL_SESSION *ss;
183
184     ss = OPENSSL_zalloc(sizeof(*ss));
185     if (ss == NULL) {
186         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
187         return NULL;
188     }
189
190     ss->verify_result = 1;      /* avoid 0 (= X509_V_OK) just in case */
191     ss->references = 1;
192     ss->timeout = 60 * 5 + 4;   /* 5 minute timeout by default */
193     ss->time = (unsigned long)time(NULL);
194     ss->lock = CRYPTO_THREAD_lock_new();
195     if (ss->lock == NULL) {
196         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
197         OPENSSL_free(ss);
198         return NULL;
199     }
200
201     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data)) {
202         CRYPTO_THREAD_lock_free(ss->lock);
203         OPENSSL_free(ss);
204         return NULL;
205     }
206     return ss;
207 }
208
209 /*
210  * Create a new SSL_SESSION and duplicate the contents of |src| into it. If
211  * ticket == 0 then no ticket information is duplicated, otherwise it is.
212  */
213 SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)
214 {
215     SSL_SESSION *dest;
216
217     dest = OPENSSL_malloc(sizeof(*src));
218     if (dest == NULL) {
219         goto err;
220     }
221     memcpy(dest, src, sizeof(*dest));
222
223     /*
224      * Set the various pointers to NULL so that we can call SSL_SESSION_free in
225      * the case of an error whilst halfway through constructing dest
226      */
227 #ifndef OPENSSL_NO_PSK
228     dest->psk_identity_hint = NULL;
229     dest->psk_identity = NULL;
230 #endif
231     dest->ciphers = NULL;
232     dest->tlsext_hostname = NULL;
233 #ifndef OPENSSL_NO_EC
234     dest->tlsext_ecpointformatlist = NULL;
235     dest->tlsext_ellipticcurvelist = NULL;
236 #endif
237     dest->tlsext_tick = NULL;
238 #ifndef OPENSSL_NO_SRP
239     dest->srp_username = NULL;
240 #endif
241     memset(&dest->ex_data, 0, sizeof(dest->ex_data));
242
243     /* We deliberately don't copy the prev and next pointers */
244     dest->prev = NULL;
245     dest->next = NULL;
246
247     dest->references = 1;
248
249     dest->lock = CRYPTO_THREAD_lock_new();
250     if (dest->lock == NULL)
251         goto err;
252
253     if (src->peer != NULL)
254         X509_up_ref(src->peer);
255
256     if (src->peer_chain != NULL) {
257         dest->peer_chain = X509_chain_up_ref(src->peer_chain);
258         if (dest->peer_chain == NULL)
259             goto err;
260     }
261
262 #ifndef OPENSSL_NO_PSK
263     if (src->psk_identity_hint) {
264         dest->psk_identity_hint = OPENSSL_strdup(src->psk_identity_hint);
265         if (dest->psk_identity_hint == NULL) {
266             goto err;
267         }
268     }
269     if (src->psk_identity) {
270         dest->psk_identity = OPENSSL_strdup(src->psk_identity);
271         if (dest->psk_identity == NULL) {
272             goto err;
273         }
274     }
275 #endif
276
277     if(src->ciphers != NULL) {
278         dest->ciphers = sk_SSL_CIPHER_dup(src->ciphers);
279         if (dest->ciphers == NULL)
280             goto err;
281     }
282
283     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
284                                             &dest->ex_data, &src->ex_data)) {
285         goto err;
286     }
287
288     if (src->tlsext_hostname) {
289         dest->tlsext_hostname = OPENSSL_strdup(src->tlsext_hostname);
290         if (dest->tlsext_hostname == NULL) {
291             goto err;
292         }
293     }
294 #ifndef OPENSSL_NO_EC
295     if (src->tlsext_ecpointformatlist) {
296         dest->tlsext_ecpointformatlist =
297             OPENSSL_memdup(src->tlsext_ecpointformatlist,
298                        src->tlsext_ecpointformatlist_length);
299         if (dest->tlsext_ecpointformatlist == NULL)
300             goto err;
301     }
302     if (src->tlsext_ellipticcurvelist) {
303         dest->tlsext_ellipticcurvelist =
304             OPENSSL_memdup(src->tlsext_ellipticcurvelist,
305                        src->tlsext_ellipticcurvelist_length);
306         if (dest->tlsext_ellipticcurvelist == NULL)
307             goto err;
308     }
309 #endif
310
311     if (ticket != 0) {
312         dest->tlsext_tick = OPENSSL_memdup(src->tlsext_tick, src->tlsext_ticklen);
313         if(dest->tlsext_tick == NULL)
314             goto err;
315     } else {
316         dest->tlsext_tick_lifetime_hint = 0;
317         dest->tlsext_ticklen = 0;
318     }
319
320 #ifndef OPENSSL_NO_SRP
321     if (src->srp_username) {
322         dest->srp_username = OPENSSL_strdup(src->srp_username);
323         if (dest->srp_username == NULL) {
324             goto err;
325         }
326     }
327 #endif
328
329     return dest;
330 err:
331     SSLerr(SSL_F_SSL_SESSION_DUP, ERR_R_MALLOC_FAILURE);
332     SSL_SESSION_free(dest);
333     return NULL;
334 }
335
336 const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
337                                         unsigned int *len)
338 {
339     if (len)
340         *len = s->session_id_length;
341     return s->session_id;
342 }
343
344 unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
345 {
346     return s->compress_meth;
347 }
348
349 /*
350  * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
351  * the ID with random junk repeatedly until we have no conflict is going to
352  * complete in one iteration pretty much "most" of the time (btw:
353  * understatement). So, if it takes us 10 iterations and we still can't avoid
354  * a conflict - well that's a reasonable point to call it quits. Either the
355  * RAND code is broken or someone is trying to open roughly very close to
356  * 2^256 SSL sessions to our server. How you might store that many sessions
357  * is perhaps a more interesting question ...
358  */
359
360 #define MAX_SESS_ID_ATTEMPTS 10
361 static int def_generate_session_id(const SSL *ssl, unsigned char *id,
362                                    unsigned int *id_len)
363 {
364     unsigned int retry = 0;
365     do
366         if (RAND_bytes(id, *id_len) <= 0)
367             return 0;
368     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
369            (++retry < MAX_SESS_ID_ATTEMPTS)) ;
370     if (retry < MAX_SESS_ID_ATTEMPTS)
371         return 1;
372     /* else - woops a session_id match */
373     /*
374      * XXX We should also check the external cache -- but the probability of
375      * a collision is negligible, and we could not prevent the concurrent
376      * creation of sessions with identical IDs since we currently don't have
377      * means to atomically check whether a session ID already exists and make
378      * a reservation for it if it does not (this problem applies to the
379      * internal cache as well).
380      */
381     return 0;
382 }
383
384 int ssl_get_new_session(SSL *s, int session)
385 {
386     /* This gets used by clients and servers. */
387
388     unsigned int tmp;
389     SSL_SESSION *ss = NULL;
390     GEN_SESSION_CB cb = def_generate_session_id;
391
392     if ((ss = SSL_SESSION_new()) == NULL)
393         return (0);
394
395     /* If the context has a default timeout, use it */
396     if (s->session_ctx->session_timeout == 0)
397         ss->timeout = SSL_get_default_timeout(s);
398     else
399         ss->timeout = s->session_ctx->session_timeout;
400
401     SSL_SESSION_free(s->session);
402     s->session = NULL;
403
404     if (session) {
405         if (s->version == SSL3_VERSION) {
406             ss->ssl_version = SSL3_VERSION;
407             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
408         } else if (s->version == TLS1_VERSION) {
409             ss->ssl_version = TLS1_VERSION;
410             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
411         } else if (s->version == TLS1_1_VERSION) {
412             ss->ssl_version = TLS1_1_VERSION;
413             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
414         } else if (s->version == TLS1_2_VERSION) {
415             ss->ssl_version = TLS1_2_VERSION;
416             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
417         } else if (s->version == DTLS1_BAD_VER) {
418             ss->ssl_version = DTLS1_BAD_VER;
419             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
420         } else if (s->version == DTLS1_VERSION) {
421             ss->ssl_version = DTLS1_VERSION;
422             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
423         } else if (s->version == DTLS1_2_VERSION) {
424             ss->ssl_version = DTLS1_2_VERSION;
425             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
426         } else {
427             SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_UNSUPPORTED_SSL_VERSION);
428             SSL_SESSION_free(ss);
429             return (0);
430         }
431
432         /*-
433          * If RFC5077 ticket, use empty session ID (as server).
434          * Note that:
435          * (a) ssl_get_prev_session() does lookahead into the
436          *     ClientHello extensions to find the session ticket.
437          *     When ssl_get_prev_session() fails, s3_srvr.c calls
438          *     ssl_get_new_session() in ssl3_get_client_hello().
439          *     At that point, it has not yet parsed the extensions,
440          *     however, because of the lookahead, it already knows
441          *     whether a ticket is expected or not.
442          *
443          * (b) s3_clnt.c calls ssl_get_new_session() before parsing
444          *     ServerHello extensions, and before recording the session
445          *     ID received from the server, so this block is a noop.
446          */
447         if (s->tlsext_ticket_expected) {
448             ss->session_id_length = 0;
449             goto sess_id_done;
450         }
451
452         /* Choose which callback will set the session ID */
453         CRYPTO_THREAD_read_lock(s->lock);
454         CRYPTO_THREAD_read_lock(s->session_ctx->lock);
455         if (s->generate_session_id)
456             cb = s->generate_session_id;
457         else if (s->session_ctx->generate_session_id)
458             cb = s->session_ctx->generate_session_id;
459         CRYPTO_THREAD_unlock(s->session_ctx->lock);
460         CRYPTO_THREAD_unlock(s->lock);
461         /* Choose a session ID */
462         tmp = ss->session_id_length;
463         if (!cb(s, ss->session_id, &tmp)) {
464             /* The callback failed */
465             SSLerr(SSL_F_SSL_GET_NEW_SESSION,
466                    SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
467             SSL_SESSION_free(ss);
468             return (0);
469         }
470         /*
471          * Don't allow the callback to set the session length to zero. nor
472          * set it higher than it was.
473          */
474         if (tmp == 0 || tmp > ss->session_id_length) {
475             /* The callback set an illegal length */
476             SSLerr(SSL_F_SSL_GET_NEW_SESSION,
477                    SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
478             SSL_SESSION_free(ss);
479             return (0);
480         }
481         ss->session_id_length = tmp;
482         /* Finally, check for a conflict */
483         if (SSL_has_matching_session_id(s, ss->session_id,
484                                         ss->session_id_length)) {
485             SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_SSL_SESSION_ID_CONFLICT);
486             SSL_SESSION_free(ss);
487             return (0);
488         }
489
490  sess_id_done:
491         if (s->tlsext_hostname) {
492             ss->tlsext_hostname = OPENSSL_strdup(s->tlsext_hostname);
493             if (ss->tlsext_hostname == NULL) {
494                 SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
495                 SSL_SESSION_free(ss);
496                 return 0;
497             }
498         }
499     } else {
500         ss->session_id_length = 0;
501     }
502
503     if (s->sid_ctx_length > sizeof ss->sid_ctx) {
504         SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
505         SSL_SESSION_free(ss);
506         return 0;
507     }
508     memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
509     ss->sid_ctx_length = s->sid_ctx_length;
510     s->session = ss;
511     ss->ssl_version = s->version;
512     ss->verify_result = X509_V_OK;
513
514     /* If client supports extended master secret set it in session */
515     if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)
516         ss->flags |= SSL_SESS_FLAG_EXTMS;
517
518     return (1);
519 }
520
521 /*-
522  * ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
523  * connection. It is only called by servers.
524  *
525  *   ext: ClientHello extensions (including length prefix)
526  *   session_id: ClientHello session ID.
527  *
528  * Returns:
529  *   -1: error
530  *    0: a session may have been found.
531  *
532  * Side effects:
533  *   - If a session is found then s->session is pointed at it (after freeing an
534  *     existing session if need be) and s->verify_result is set from the session.
535  *   - Both for new and resumed sessions, s->tlsext_ticket_expected is set to 1
536  *     if the server should issue a new session ticket (to 0 otherwise).
537  */
538 int ssl_get_prev_session(SSL *s, const PACKET *ext, const PACKET *session_id)
539 {
540     /* This is used only by servers. */
541
542     SSL_SESSION *ret = NULL;
543     int fatal = 0;
544     int try_session_cache = 1;
545     int r;
546
547     if (PACKET_remaining(session_id) == 0)
548         try_session_cache = 0;
549
550     /* sets s->tlsext_ticket_expected and extended master secret flag */
551     r = tls_check_serverhello_tlsext_early(s, ext, session_id, &ret);
552     switch (r) {
553     case -1:                   /* Error during processing */
554         fatal = 1;
555         goto err;
556     case 0:                    /* No ticket found */
557     case 1:                    /* Zero length ticket found */
558         break;                  /* Ok to carry on processing session id. */
559     case 2:                    /* Ticket found but not decrypted. */
560     case 3:                    /* Ticket decrypted, *ret has been set. */
561         try_session_cache = 0;
562         break;
563     default:
564         abort();
565     }
566
567     if (try_session_cache &&
568         ret == NULL &&
569         !(s->session_ctx->session_cache_mode &
570           SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
571         SSL_SESSION data;
572         size_t local_len;
573         data.ssl_version = s->version;
574         if (!PACKET_copy_all(session_id, data.session_id,
575                              sizeof(data.session_id),
576                              &local_len)) {
577             goto err;
578         }
579         data.session_id_length = local_len;
580         CRYPTO_THREAD_read_lock(s->session_ctx->lock);
581         ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
582         if (ret != NULL) {
583             /* don't allow other threads to steal it: */
584             SSL_SESSION_up_ref(ret);
585         }
586         CRYPTO_THREAD_unlock(s->session_ctx->lock);
587         if (ret == NULL)
588             s->session_ctx->stats.sess_miss++;
589     }
590
591     if (try_session_cache &&
592         ret == NULL && s->session_ctx->get_session_cb != NULL) {
593         int copy = 1;
594         ret = s->session_ctx->get_session_cb(s, PACKET_data(session_id),
595                                              PACKET_remaining(session_id),
596                                              &copy);
597
598         if (ret != NULL) {
599             s->session_ctx->stats.sess_cb_hit++;
600
601             /*
602              * Increment reference count now if the session callback asks us
603              * to do so (note that if the session structures returned by the
604              * callback are shared between threads, it must handle the
605              * reference count itself [i.e. copy == 0], or things won't be
606              * thread-safe).
607              */
608             if (copy)
609                 SSL_SESSION_up_ref(ret);
610
611             /*
612              * Add the externally cached session to the internal cache as
613              * well if and only if we are supposed to.
614              */
615             if (!
616                 (s->session_ctx->session_cache_mode &
617                  SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
618                 /*
619                  * The following should not return 1, otherwise, things are
620                  * very strange
621                  */
622                 if (SSL_CTX_add_session(s->session_ctx, ret))
623                     goto err;
624             }
625         }
626     }
627
628     if (ret == NULL)
629         goto err;
630
631     /* Now ret is non-NULL and we own one of its reference counts. */
632
633     if (ret->sid_ctx_length != s->sid_ctx_length
634         || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
635         /*
636          * We have the session requested by the client, but we don't want to
637          * use it in this context.
638          */
639         goto err;               /* treat like cache miss */
640     }
641
642     if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
643         /*
644          * We can't be sure if this session is being used out of context,
645          * which is especially important for SSL_VERIFY_PEER. The application
646          * should have used SSL[_CTX]_set_session_id_context. For this error
647          * case, we generate an error instead of treating the event like a
648          * cache miss (otherwise it would be easy for applications to
649          * effectively disable the session cache by accident without anyone
650          * noticing).
651          */
652
653         SSLerr(SSL_F_SSL_GET_PREV_SESSION,
654                SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
655         fatal = 1;
656         goto err;
657     }
658
659     if (ret->cipher == NULL) {
660         unsigned char buf[5], *p;
661         unsigned long l;
662
663         p = buf;
664         l = ret->cipher_id;
665         l2n(l, p);
666         if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR)
667             ret->cipher = ssl_get_cipher_by_char(s, &(buf[2]));
668         else
669             ret->cipher = ssl_get_cipher_by_char(s, &(buf[1]));
670         if (ret->cipher == NULL)
671             goto err;
672     }
673
674     if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
675         s->session_ctx->stats.sess_timeout++;
676         if (try_session_cache) {
677             /* session was from the cache, so remove it */
678             SSL_CTX_remove_session(s->session_ctx, ret);
679         }
680         goto err;
681     }
682
683     /* Check extended master secret extension consistency */
684     if (ret->flags & SSL_SESS_FLAG_EXTMS) {
685         /* If old session includes extms, but new does not: abort handshake */
686         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
687             SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_INCONSISTENT_EXTMS);
688             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
689             fatal = 1;
690             goto err;
691         }
692     } else if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {
693         /* If new session includes extms, but old does not: do not resume */
694         goto err;
695     }
696
697     s->session_ctx->stats.sess_hit++;
698
699     SSL_SESSION_free(s->session);
700     s->session = ret;
701     s->verify_result = s->session->verify_result;
702     return 1;
703
704  err:
705     if (ret != NULL) {
706         SSL_SESSION_free(ret);
707
708         if (!try_session_cache) {
709             /*
710              * The session was from a ticket, so we should issue a ticket for
711              * the new session
712              */
713             s->tlsext_ticket_expected = 1;
714         }
715     }
716     if (fatal)
717         return -1;
718     else
719         return 0;
720 }
721
722 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
723 {
724     int ret = 0;
725     SSL_SESSION *s;
726
727     /*
728      * add just 1 reference count for the SSL_CTX's session cache even though
729      * it has two ways of access: each session is in a doubly linked list and
730      * an lhash
731      */
732     SSL_SESSION_up_ref(c);
733     /*
734      * if session c is in already in cache, we take back the increment later
735      */
736
737     CRYPTO_THREAD_write_lock(ctx->lock);
738     s = lh_SSL_SESSION_insert(ctx->sessions, c);
739
740     /*
741      * s != NULL iff we already had a session with the given PID. In this
742      * case, s == c should hold (then we did not really modify
743      * ctx->sessions), or we're in trouble.
744      */
745     if (s != NULL && s != c) {
746         /* We *are* in trouble ... */
747         SSL_SESSION_list_remove(ctx, s);
748         SSL_SESSION_free(s);
749         /*
750          * ... so pretend the other session did not exist in cache (we cannot
751          * handle two SSL_SESSION structures with identical session ID in the
752          * same cache, which could happen e.g. when two threads concurrently
753          * obtain the same session from an external cache)
754          */
755         s = NULL;
756     }
757
758     /* Put at the head of the queue unless it is already in the cache */
759     if (s == NULL)
760         SSL_SESSION_list_add(ctx, c);
761
762     if (s != NULL) {
763         /*
764          * existing cache entry -- decrement previously incremented reference
765          * count because it already takes into account the cache
766          */
767
768         SSL_SESSION_free(s);    /* s == c */
769         ret = 0;
770     } else {
771         /*
772          * new cache entry -- remove old ones if cache has become too large
773          */
774
775         ret = 1;
776
777         if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
778             while (SSL_CTX_sess_number(ctx) >
779                    SSL_CTX_sess_get_cache_size(ctx)) {
780                 if (!remove_session_lock(ctx, ctx->session_cache_tail, 0))
781                     break;
782                 else
783                     ctx->stats.sess_cache_full++;
784             }
785         }
786     }
787     CRYPTO_THREAD_unlock(ctx->lock);
788     return ret;
789 }
790
791 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
792 {
793     return remove_session_lock(ctx, c, 1);
794 }
795
796 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
797 {
798     SSL_SESSION *r;
799     int ret = 0;
800
801     if ((c != NULL) && (c->session_id_length != 0)) {
802         if (lck)
803             CRYPTO_THREAD_write_lock(ctx->lock);
804         if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
805             ret = 1;
806             r = lh_SSL_SESSION_delete(ctx->sessions, c);
807             SSL_SESSION_list_remove(ctx, c);
808         }
809
810         if (lck)
811             CRYPTO_THREAD_unlock(ctx->lock);
812
813         if (ret) {
814             r->not_resumable = 1;
815             if (ctx->remove_session_cb != NULL)
816                 ctx->remove_session_cb(ctx, r);
817             SSL_SESSION_free(r);
818         }
819     } else
820         ret = 0;
821     return (ret);
822 }
823
824 void SSL_SESSION_free(SSL_SESSION *ss)
825 {
826     int i;
827
828     if (ss == NULL)
829         return;
830
831     CRYPTO_atomic_add(&ss->references, -1, &i, ss->lock);
832     REF_PRINT_COUNT("SSL_SESSION", ss);
833     if (i > 0)
834         return;
835     REF_ASSERT_ISNT(i < 0);
836
837     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
838
839     OPENSSL_cleanse(ss->master_key, sizeof ss->master_key);
840     OPENSSL_cleanse(ss->session_id, sizeof ss->session_id);
841     X509_free(ss->peer);
842     sk_X509_pop_free(ss->peer_chain, X509_free);
843     sk_SSL_CIPHER_free(ss->ciphers);
844     OPENSSL_free(ss->tlsext_hostname);
845     OPENSSL_free(ss->tlsext_tick);
846 #ifndef OPENSSL_NO_EC
847     ss->tlsext_ecpointformatlist_length = 0;
848     OPENSSL_free(ss->tlsext_ecpointformatlist);
849     ss->tlsext_ellipticcurvelist_length = 0;
850     OPENSSL_free(ss->tlsext_ellipticcurvelist);
851 #endif                         /* OPENSSL_NO_EC */
852 #ifndef OPENSSL_NO_PSK
853     OPENSSL_free(ss->psk_identity_hint);
854     OPENSSL_free(ss->psk_identity);
855 #endif
856 #ifndef OPENSSL_NO_SRP
857     OPENSSL_free(ss->srp_username);
858 #endif
859     CRYPTO_THREAD_lock_free(ss->lock);
860     OPENSSL_clear_free(ss, sizeof(*ss));
861 }
862
863 int SSL_SESSION_up_ref(SSL_SESSION *ss)
864 {
865     int i;
866
867     if (CRYPTO_atomic_add(&ss->references, 1, &i, ss->lock) <= 0)
868         return 0;
869
870     REF_PRINT_COUNT("SSL_SESSION", ss);
871     REF_ASSERT_ISNT(i < 2);
872     return ((i > 1) ? 1 : 0);
873 }
874
875 int SSL_set_session(SSL *s, SSL_SESSION *session)
876 {
877     int ret = 0;
878     if (session != NULL) {
879         if (s->ctx->method != s->method) {
880             if (!SSL_set_ssl_method(s, s->ctx->method))
881                 return (0);
882         }
883
884         SSL_SESSION_up_ref(session);
885         SSL_SESSION_free(s->session);
886         s->session = session;
887         s->verify_result = s->session->verify_result;
888         ret = 1;
889     } else {
890         SSL_SESSION_free(s->session);
891         s->session = NULL;
892         if (s->ctx->method != s->method) {
893             if (!SSL_set_ssl_method(s, s->ctx->method))
894                 return (0);
895         }
896         ret = 1;
897     }
898     return (ret);
899 }
900
901 long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
902 {
903     if (s == NULL)
904         return (0);
905     s->timeout = t;
906     return (1);
907 }
908
909 long SSL_SESSION_get_timeout(const SSL_SESSION *s)
910 {
911     if (s == NULL)
912         return (0);
913     return (s->timeout);
914 }
915
916 long SSL_SESSION_get_time(const SSL_SESSION *s)
917 {
918     if (s == NULL)
919         return (0);
920     return (s->time);
921 }
922
923 long SSL_SESSION_set_time(SSL_SESSION *s, long t)
924 {
925     if (s == NULL)
926         return (0);
927     s->time = t;
928     return (t);
929 }
930
931 const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s)
932 {
933     return s->tlsext_hostname;
934 }
935
936 int SSL_SESSION_has_ticket(const SSL_SESSION *s)
937 {
938     return (s->tlsext_ticklen > 0) ? 1 : 0;
939 }
940
941 unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
942 {
943     return s->tlsext_tick_lifetime_hint;
944 }
945
946 void SSL_SESSION_get0_ticket(const SSL_SESSION *s, unsigned char **tick,
947                             size_t *len)
948 {
949     *len = s->tlsext_ticklen;
950     if (tick != NULL)
951         *tick = s->tlsext_tick;
952 }
953
954 X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
955 {
956     return s->peer;
957 }
958
959 int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
960                                 unsigned int sid_ctx_len)
961 {
962     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
963         SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
964                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
965         return 0;
966     }
967     s->sid_ctx_length = sid_ctx_len;
968     memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
969
970     return 1;
971 }
972
973 long SSL_CTX_set_timeout(SSL_CTX *s, long t)
974 {
975     long l;
976     if (s == NULL)
977         return (0);
978     l = s->session_timeout;
979     s->session_timeout = t;
980     return (l);
981 }
982
983 long SSL_CTX_get_timeout(const SSL_CTX *s)
984 {
985     if (s == NULL)
986         return (0);
987     return (s->session_timeout);
988 }
989
990 int SSL_set_session_secret_cb(SSL *s,
991                               int (*tls_session_secret_cb) (SSL *s,
992                                                             void *secret,
993                                                             int *secret_len,
994                                                             STACK_OF(SSL_CIPHER)
995                                                             *peer_ciphers,
996                                                             const SSL_CIPHER
997                                                             **cipher,
998                                                             void *arg),
999                               void *arg)
1000 {
1001     if (s == NULL)
1002         return (0);
1003     s->tls_session_secret_cb = tls_session_secret_cb;
1004     s->tls_session_secret_cb_arg = arg;
1005     return (1);
1006 }
1007
1008 int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
1009                                   void *arg)
1010 {
1011     if (s == NULL)
1012         return (0);
1013     s->tls_session_ticket_ext_cb = cb;
1014     s->tls_session_ticket_ext_cb_arg = arg;
1015     return (1);
1016 }
1017
1018 int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
1019 {
1020     if (s->version >= TLS1_VERSION) {
1021         OPENSSL_free(s->tlsext_session_ticket);
1022         s->tlsext_session_ticket = NULL;
1023         s->tlsext_session_ticket =
1024             OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
1025         if (s->tlsext_session_ticket == NULL) {
1026             SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE);
1027             return 0;
1028         }
1029
1030         if (ext_data) {
1031             s->tlsext_session_ticket->length = ext_len;
1032             s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1;
1033             memcpy(s->tlsext_session_ticket->data, ext_data, ext_len);
1034         } else {
1035             s->tlsext_session_ticket->length = 0;
1036             s->tlsext_session_ticket->data = NULL;
1037         }
1038
1039         return 1;
1040     }
1041
1042     return 0;
1043 }
1044
1045 typedef struct timeout_param_st {
1046     SSL_CTX *ctx;
1047     long time;
1048     LHASH_OF(SSL_SESSION) *cache;
1049 } TIMEOUT_PARAM;
1050
1051 static void timeout_cb(SSL_SESSION *s, TIMEOUT_PARAM *p)
1052 {
1053     if ((p->time == 0) || (p->time > (s->time + s->timeout))) { /* timeout */
1054         /*
1055          * The reason we don't call SSL_CTX_remove_session() is to save on
1056          * locking overhead
1057          */
1058         (void)lh_SSL_SESSION_delete(p->cache, s);
1059         SSL_SESSION_list_remove(p->ctx, s);
1060         s->not_resumable = 1;
1061         if (p->ctx->remove_session_cb != NULL)
1062             p->ctx->remove_session_cb(p->ctx, s);
1063         SSL_SESSION_free(s);
1064     }
1065 }
1066
1067 IMPLEMENT_LHASH_DOALL_ARG(SSL_SESSION, TIMEOUT_PARAM);
1068
1069 void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1070 {
1071     unsigned long i;
1072     TIMEOUT_PARAM tp;
1073
1074     tp.ctx = s;
1075     tp.cache = s->sessions;
1076     if (tp.cache == NULL)
1077         return;
1078     tp.time = t;
1079     CRYPTO_THREAD_write_lock(s->lock);
1080     i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
1081     CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
1082     lh_SSL_SESSION_doall_TIMEOUT_PARAM(tp.cache, timeout_cb, &tp);
1083     CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
1084     CRYPTO_THREAD_unlock(s->lock);
1085 }
1086
1087 int ssl_clear_bad_session(SSL *s)
1088 {
1089     if ((s->session != NULL) &&
1090         !(s->shutdown & SSL_SENT_SHUTDOWN) &&
1091         !(SSL_in_init(s) || SSL_in_before(s))) {
1092         SSL_CTX_remove_session(s->ctx, s->session);
1093         return (1);
1094     } else
1095         return (0);
1096 }
1097
1098 /* locked by SSL_CTX in the calling function */
1099 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1100 {
1101     if ((s->next == NULL) || (s->prev == NULL))
1102         return;
1103
1104     if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1105         /* last element in list */
1106         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1107             /* only one element in list */
1108             ctx->session_cache_head = NULL;
1109             ctx->session_cache_tail = NULL;
1110         } else {
1111             ctx->session_cache_tail = s->prev;
1112             s->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1113         }
1114     } else {
1115         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1116             /* first element in list */
1117             ctx->session_cache_head = s->next;
1118             s->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1119         } else {
1120             /* middle of list */
1121             s->next->prev = s->prev;
1122             s->prev->next = s->next;
1123         }
1124     }
1125     s->prev = s->next = NULL;
1126 }
1127
1128 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1129 {
1130     if ((s->next != NULL) && (s->prev != NULL))
1131         SSL_SESSION_list_remove(ctx, s);
1132
1133     if (ctx->session_cache_head == NULL) {
1134         ctx->session_cache_head = s;
1135         ctx->session_cache_tail = s;
1136         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1137         s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1138     } else {
1139         s->next = ctx->session_cache_head;
1140         s->next->prev = s;
1141         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1142         ctx->session_cache_head = s;
1143     }
1144 }
1145
1146 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1147                              int (*cb) (struct ssl_st *ssl,
1148                                         SSL_SESSION *sess))
1149 {
1150     ctx->new_session_cb = cb;
1151 }
1152
1153 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (SSL *ssl, SSL_SESSION *sess) {
1154     return ctx->new_session_cb;
1155 }
1156
1157 void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1158                                 void (*cb) (SSL_CTX *ctx, SSL_SESSION *sess))
1159 {
1160     ctx->remove_session_cb = cb;
1161 }
1162
1163 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (SSL_CTX *ctx,
1164                                                   SSL_SESSION *sess) {
1165     return ctx->remove_session_cb;
1166 }
1167
1168 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1169                              SSL_SESSION *(*cb) (struct ssl_st *ssl,
1170                                                  const unsigned char *data,
1171                                                  int len, int *copy))
1172 {
1173     ctx->get_session_cb = cb;
1174 }
1175
1176 SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (SSL *ssl,
1177                                                        const unsigned char *data,
1178                                                        int len, int *copy) {
1179     return ctx->get_session_cb;
1180 }
1181
1182 void SSL_CTX_set_info_callback(SSL_CTX *ctx,
1183                                void (*cb) (const SSL *ssl, int type, int val))
1184 {
1185     ctx->info_callback = cb;
1186 }
1187
1188 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
1189                                                  int val) {
1190     return ctx->info_callback;
1191 }
1192
1193 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1194                                 int (*cb) (SSL *ssl, X509 **x509,
1195                                            EVP_PKEY **pkey))
1196 {
1197     ctx->client_cert_cb = cb;
1198 }
1199
1200 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
1201                                                  EVP_PKEY **pkey) {
1202     return ctx->client_cert_cb;
1203 }
1204
1205 #ifndef OPENSSL_NO_ENGINE
1206 int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1207 {
1208     if (!ENGINE_init(e)) {
1209         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, ERR_R_ENGINE_LIB);
1210         return 0;
1211     }
1212     if (!ENGINE_get_ssl_client_cert_function(e)) {
1213         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1214                SSL_R_NO_CLIENT_CERT_METHOD);
1215         ENGINE_finish(e);
1216         return 0;
1217     }
1218     ctx->client_cert_engine = e;
1219     return 1;
1220 }
1221 #endif
1222
1223 void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1224                                     int (*cb) (SSL *ssl,
1225                                                unsigned char *cookie,
1226                                                unsigned int *cookie_len))
1227 {
1228     ctx->app_gen_cookie_cb = cb;
1229 }
1230
1231 void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1232                                   int (*cb) (SSL *ssl, const unsigned char *cookie,
1233                                              unsigned int cookie_len))
1234 {
1235     ctx->app_verify_cookie_cb = cb;
1236 }
1237
1238 IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION,
1239                  SSL_SESSION)