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