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