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