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