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