ssl_sess.c revision 1.59
1/* $OpenBSD: ssl_sess.c,v 1.59 2017/01/23 04:55:27 beck 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	if ((ss = calloc(1, sizeof(*ss))) == NULL) {
203		SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
204		return (NULL);
205	}
206	if ((ss->internal = calloc(1, sizeof(*ss->internal))) == NULL) {
207		free(ss);
208		SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
209		return (NULL);
210	}
211
212	ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */
213	ss->references = 1;
214	ss->timeout=60*5+4; /* 5 minute timeout by default */
215	ss->time = time(NULL);
216	ss->prev = NULL;
217	ss->next = NULL;
218	ss->tlsext_hostname = NULL;
219
220	ss->internal->tlsext_ecpointformatlist_length = 0;
221	ss->internal->tlsext_ecpointformatlist = NULL;
222	ss->internal->tlsext_ellipticcurvelist_length = 0;
223	ss->internal->tlsext_ellipticcurvelist = NULL;
224
225	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
226
227	return (ss);
228}
229
230const unsigned char *
231SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
232{
233	if (len)
234		*len = s->session_id_length;
235	return s->session_id;
236}
237
238unsigned int
239SSL_SESSION_get_compress_id(const SSL_SESSION *s)
240{
241	return 0;
242}
243
244/*
245 * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
246 * the ID with random gunk repeatedly until we have no conflict is going to
247 * complete in one iteration pretty much "most" of the time (btw:
248 * understatement). So, if it takes us 10 iterations and we still can't avoid
249 * a conflict - well that's a reasonable point to call it quits. Either the
250 * arc4random code is broken or someone is trying to open roughly very close to
251 * 2^128 (or 2^256) SSL sessions to our server. How you might store that many
252 * sessions is perhaps a more interesting question...
253 */
254
255#define MAX_SESS_ID_ATTEMPTS 10
256
257static int
258def_generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
259{
260	unsigned int retry = 0;
261
262	do {
263		arc4random_buf(id, *id_len);
264	} while (SSL_has_matching_session_id(ssl, id, *id_len) &&
265	    (++retry < MAX_SESS_ID_ATTEMPTS));
266
267	if (retry < MAX_SESS_ID_ATTEMPTS)
268		return 1;
269
270	/* else - woops a session_id match */
271	/* XXX We should also check the external cache --
272	 * but the probability of a collision is negligible, and
273	 * we could not prevent the concurrent creation of sessions
274	 * with identical IDs since we currently don't have means
275	 * to atomically check whether a session ID already exists
276	 * and make a reservation for it if it does not
277	 * (this problem applies to the internal cache as well).
278	 */
279	return 0;
280}
281
282int
283ssl_get_new_session(SSL *s, int session)
284{
285	unsigned int tmp;
286	SSL_SESSION *ss = NULL;
287	GEN_SESSION_CB cb = def_generate_session_id;
288
289	/* This gets used by clients and servers. */
290
291	if ((ss = SSL_SESSION_new()) == NULL)
292		return (0);
293
294	/* If the context has a default timeout, use it */
295	if (s->session_ctx->session_timeout == 0)
296		ss->timeout = SSL_get_default_timeout(s);
297	else
298		ss->timeout = s->session_ctx->session_timeout;
299
300	if (s->session != NULL) {
301		SSL_SESSION_free(s->session);
302		s->session = NULL;
303	}
304
305	if (session) {
306		switch (s->version) {
307		case TLS1_VERSION:
308		case TLS1_1_VERSION:
309		case TLS1_2_VERSION:
310		case DTLS1_VERSION:
311			ss->ssl_version = s->version;
312			ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
313			break;
314		default:
315			SSLerr(SSL_F_SSL_GET_NEW_SESSION,
316			    SSL_R_UNSUPPORTED_SSL_VERSION);
317			SSL_SESSION_free(ss);
318			return (0);
319		}
320
321		/* If RFC4507 ticket use empty session ID. */
322		if (s->tlsext_ticket_expected) {
323			ss->session_id_length = 0;
324			goto sess_id_done;
325		}
326
327		/* Choose which callback will set the session ID. */
328		CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
329		if (s->internal->generate_session_id)
330			cb = s->internal->generate_session_id;
331		else if (s->session_ctx->internal->generate_session_id)
332			cb = s->session_ctx->internal->generate_session_id;
333		CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
334
335		/* Choose a session ID. */
336		tmp = ss->session_id_length;
337		if (!cb(s, ss->session_id, &tmp)) {
338			/* The callback failed */
339			SSLerr(SSL_F_SSL_GET_NEW_SESSION,
340			SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
341			SSL_SESSION_free(ss);
342			return (0);
343		}
344
345		/*
346		 * Don't allow the callback to set the session length to zero.
347		 * nor set it higher than it was.
348		 */
349		if (!tmp || (tmp > ss->session_id_length)) {
350			/* The callback set an illegal length */
351			SSLerr(SSL_F_SSL_GET_NEW_SESSION,
352			SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
353			SSL_SESSION_free(ss);
354			return (0);
355		}
356		ss->session_id_length = tmp;
357
358		/* Finally, check for a conflict. */
359		if (SSL_has_matching_session_id(s, ss->session_id,
360			ss->session_id_length)) {
361			SSLerr(SSL_F_SSL_GET_NEW_SESSION,
362			SSL_R_SSL_SESSION_ID_CONFLICT);
363			SSL_SESSION_free(ss);
364			return (0);
365		}
366
367sess_id_done:
368		if (s->tlsext_hostname) {
369			ss->tlsext_hostname = strdup(s->tlsext_hostname);
370			if (ss->tlsext_hostname == NULL) {
371				SSLerr(SSL_F_SSL_GET_NEW_SESSION,
372				    ERR_R_INTERNAL_ERROR);
373				SSL_SESSION_free(ss);
374				return 0;
375			}
376		}
377	} else {
378		ss->session_id_length = 0;
379	}
380
381	if (s->sid_ctx_length > sizeof ss->sid_ctx) {
382		SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
383		SSL_SESSION_free(ss);
384		return 0;
385	}
386
387	memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
388	ss->sid_ctx_length = s->sid_ctx_length;
389	s->session = ss;
390	ss->ssl_version = s->version;
391	ss->verify_result = X509_V_OK;
392
393	return (1);
394}
395
396/*
397 * ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
398 * connection. It is only called by servers.
399 *
400 *   session_id: points at the session ID in the ClientHello. This code will
401 *       read past the end of this in order to parse out the session ticket
402 *       extension, if any.
403 *   len: the length of the session ID.
404 *   limit: a pointer to the first byte after the ClientHello.
405 *
406 * Returns:
407 *   -1: error
408 *    0: a session may have been found.
409 *
410 * Side effects:
411 *   - If a session is found then s->session is pointed at it (after freeing
412 *     an existing session if need be) and s->verify_result is set from the
413 *     session.
414 *   - Both for new and resumed sessions, s->tlsext_ticket_expected is set
415 *     to 1 if the server should issue a new session ticket (to 0 otherwise).
416 */
417int
418ssl_get_prev_session(SSL *s, unsigned char *session_id, int len,
419    const unsigned char *limit)
420{
421	SSL_SESSION *ret = NULL;
422	int fatal = 0;
423	int try_session_cache = 1;
424	int r;
425
426	/* This is used only by servers. */
427
428	if (len > SSL_MAX_SSL_SESSION_ID_LENGTH)
429		goto err;
430
431	if (len == 0)
432		try_session_cache = 0;
433
434	/* Sets s->tlsext_ticket_expected. */
435	r = tls1_process_ticket(s, session_id, len, limit, &ret);
436	switch (r) {
437	case -1: /* Error during processing */
438		fatal = 1;
439		goto err;
440	case 0: /* No ticket found */
441	case 1: /* Zero length ticket found */
442		break; /* Ok to carry on processing session id. */
443	case 2: /* Ticket found but not decrypted. */
444	case 3: /* Ticket decrypted, *ret has been set. */
445		try_session_cache = 0;
446		break;
447	default:
448		abort();
449	}
450
451	if (try_session_cache && ret == NULL &&
452	    !(s->session_ctx->session_cache_mode &
453	     SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
454		SSL_SESSION data;
455		data.ssl_version = s->version;
456		data.session_id_length = len;
457		memcpy(data.session_id, session_id, len);
458
459		CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
460		ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
461		if (ret != NULL) {
462			/* Don't allow other threads to steal it. */
463			CRYPTO_add(&ret->references, 1,
464			    CRYPTO_LOCK_SSL_SESSION);
465		}
466		CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
467
468		if (ret == NULL)
469			s->session_ctx->internal->stats.sess_miss++;
470	}
471
472	if (try_session_cache && ret == NULL &&
473	    s->session_ctx->internal->get_session_cb != NULL) {
474		int copy = 1;
475
476		if ((ret = s->session_ctx->internal->get_session_cb(s,
477		    session_id, len, &copy))) {
478			s->session_ctx->internal->stats.sess_cb_hit++;
479
480			/*
481			 * Increment reference count now if the session
482			 * callback asks us to do so (note that if the session
483			 * structures returned by the callback are shared
484			 * between threads, it must handle the reference count
485			 * itself [i.e. copy == 0], or things won't be
486			 * thread-safe).
487			 */
488			if (copy)
489				CRYPTO_add(&ret->references, 1,
490				    CRYPTO_LOCK_SSL_SESSION);
491
492			/*
493			 * Add the externally cached session to the internal
494			 * cache as well if and only if we are supposed to.
495			 */
496			if (!(s->session_ctx->session_cache_mode &
497			    SSL_SESS_CACHE_NO_INTERNAL_STORE))
498				/*
499				 * The following should not return 1,
500				 * otherwise, things are very strange.
501				 */
502				SSL_CTX_add_session(s->session_ctx, ret);
503		}
504	}
505
506	if (ret == NULL)
507		goto err;
508
509	/* Now ret is non-NULL and we own one of its reference counts. */
510
511	if (ret->sid_ctx_length != s->sid_ctx_length ||
512	    timingsafe_memcmp(ret->sid_ctx,
513		s->sid_ctx, ret->sid_ctx_length) != 0) {
514		/* We have the session requested by the client, but we don't
515		 * want to use it in this context. */
516		goto err; /* treat like cache miss */
517	}
518
519	if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
520		/*
521		 * We can't be sure if this session is being used out of
522		 * context, which is especially important for SSL_VERIFY_PEER.
523		 * The application should have used
524		 * SSL[_CTX]_set_session_id_context.
525		 *
526		 * For this error case, we generate an error instead of treating
527		 * the event like a cache miss (otherwise it would be easy for
528		 * applications to effectively disable the session cache by
529		 * accident without anyone noticing).
530		 */
531		SSLerr(SSL_F_SSL_GET_PREV_SESSION,
532		    SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
533		fatal = 1;
534		goto err;
535	}
536
537	if (ret->cipher == NULL) {
538		ret->cipher = ssl3_get_cipher_by_id(ret->cipher_id);
539		if (ret->cipher == NULL)
540			goto err;
541	}
542
543	if (ret->timeout < (time(NULL) - ret->time)) {
544		/* timeout */
545		s->session_ctx->internal->stats.sess_timeout++;
546		if (try_session_cache) {
547			/* session was from the cache, so remove it */
548			SSL_CTX_remove_session(s->session_ctx, ret);
549		}
550		goto err;
551	}
552
553	s->session_ctx->internal->stats.sess_hit++;
554
555	if (s->session != NULL)
556		SSL_SESSION_free(s->session);
557	s->session = ret;
558	s->verify_result = s->session->verify_result;
559	return 1;
560
561err:
562	if (ret != NULL) {
563		SSL_SESSION_free(ret);
564		if (!try_session_cache) {
565			/*
566			 * The session was from a ticket, so we should
567			 * issue a ticket for the new session.
568			 */
569			s->tlsext_ticket_expected = 1;
570		}
571	}
572	if (fatal)
573		return -1;
574	else
575		return 0;
576}
577
578int
579SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
580{
581	int ret = 0;
582	SSL_SESSION *s;
583
584	/*
585	 * Add just 1 reference count for the SSL_CTX's session cache
586	 * even though it has two ways of access: each session is in a
587	 * doubly linked list and an lhash.
588	 */
589	CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
590
591	/*
592	 * If session c is in already in cache, we take back the increment
593	 * later.
594	 */
595	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
596	s = lh_SSL_SESSION_insert(ctx->sessions, c);
597
598	/*
599	 * s != NULL iff we already had a session with the given PID.
600	 * In this case, s == c should hold (then we did not really modify
601	 * ctx->sessions), or we're in trouble.
602	 */
603	if (s != NULL && s != c) {
604		/* We *are* in trouble ... */
605		SSL_SESSION_list_remove(ctx, s);
606		SSL_SESSION_free(s);
607		/*
608		 * ... so pretend the other session did not exist in cache
609		 * (we cannot handle two SSL_SESSION structures with identical
610		 * session ID in the same cache, which could happen e.g. when
611		 * two threads concurrently obtain the same session from an
612		 * external cache).
613		 */
614		s = NULL;
615	}
616
617	/* Put at the head of the queue unless it is already in the cache */
618	if (s == NULL)
619		SSL_SESSION_list_add(ctx, c);
620
621	if (s != NULL) {
622		/*
623		 * existing cache entry -- decrement previously incremented
624		 * reference count because it already takes into account the
625		 * cache.
626		 */
627		SSL_SESSION_free(s); /* s == c */
628		ret = 0;
629	} else {
630		/*
631		 * New cache entry -- remove old ones if cache has become
632		 * too large.
633		 */
634
635		ret = 1;
636
637		if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
638			while (SSL_CTX_sess_number(ctx) >
639			    SSL_CTX_sess_get_cache_size(ctx)) {
640				if (!remove_session_lock(ctx,
641				    ctx->session_cache_tail, 0))
642					break;
643				else
644					ctx->internal->stats.sess_cache_full++;
645			}
646		}
647	}
648	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
649	return (ret);
650}
651
652int
653SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
654{
655	return remove_session_lock(ctx, c, 1);
656}
657
658static int
659remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
660{
661	SSL_SESSION *r;
662	int ret = 0;
663
664	if ((c != NULL) && (c->session_id_length != 0)) {
665		if (lck)
666			CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
667		if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
668			ret = 1;
669			r = lh_SSL_SESSION_delete(ctx->sessions, c);
670			SSL_SESSION_list_remove(ctx, c);
671		}
672		if (lck)
673			CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
674
675		if (ret) {
676			r->internal->not_resumable = 1;
677			if (ctx->internal->remove_session_cb != NULL)
678				ctx->internal->remove_session_cb(ctx, r);
679			SSL_SESSION_free(r);
680		}
681	} else
682		ret = 0;
683	return (ret);
684}
685
686void
687SSL_SESSION_free(SSL_SESSION *ss)
688{
689	int i;
690
691	if (ss == NULL)
692		return;
693
694	i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
695	if (i > 0)
696		return;
697
698	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
699
700	explicit_bzero(ss->master_key, sizeof ss->master_key);
701	explicit_bzero(ss->session_id, sizeof ss->session_id);
702	if (ss->internal->sess_cert != NULL)
703		ssl_sess_cert_free(ss->internal->sess_cert);
704	X509_free(ss->peer);
705	if (ss->ciphers != NULL)
706		sk_SSL_CIPHER_free(ss->ciphers);
707	free(ss->tlsext_hostname);
708	free(ss->tlsext_tick);
709	ss->internal->tlsext_ecpointformatlist_length = 0;
710	free(ss->internal->tlsext_ecpointformatlist);
711	ss->internal->tlsext_ellipticcurvelist_length = 0;
712	free(ss->internal->tlsext_ellipticcurvelist);
713
714	explicit_bzero(ss->internal, sizeof(*ss->internal));
715	free(ss->internal);
716
717	explicit_bzero(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->internal->tls_session_secret_cb = tls_session_secret_cb;
853	s->internal->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->internal->tls_session_ticket_ext_cb = cb;
864	s->internal->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	struct lhash_st_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->internal->not_resumable = 1;
914		if (p->ctx->internal->remove_session_cb != NULL)
915			p->ctx->internal->remove_session_cb(p->ctx, s);
916		SSL_SESSION_free(s);
917	}
918}
919
920static void
921timeout_LHASH_DOALL_ARG(void *arg1, void *arg2)
922{
923	SSL_SESSION *a = arg1;
924	TIMEOUT_PARAM *b = arg2;
925
926	timeout_doall_arg(a, b);
927}
928
929/* XXX 2038 */
930void
931SSL_CTX_flush_sessions(SSL_CTX *s, long t)
932{
933	unsigned long i;
934	TIMEOUT_PARAM tp;
935
936	tp.ctx = s;
937	tp.cache = s->sessions;
938	if (tp.cache == NULL)
939		return;
940	tp.time = t;
941	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
942	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
943	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
944	lh_SSL_SESSION_doall_arg(tp.cache, timeout_LHASH_DOALL_ARG,
945	TIMEOUT_PARAM, &tp);
946	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
947	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
948}
949
950int
951ssl_clear_bad_session(SSL *s)
952{
953	if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) &&
954	    !(SSL_in_init(s) || SSL_in_before(s))) {
955		SSL_CTX_remove_session(s->ctx, s->session);
956		return (1);
957	} else
958		return (0);
959}
960
961/* locked by SSL_CTX in the calling function */
962static void
963SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
964{
965	if ((s->next == NULL) || (s->prev == NULL))
966		return;
967
968	if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
969		/* last element in list */
970		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
971			/* only one element in list */
972			ctx->session_cache_head = NULL;
973			ctx->session_cache_tail = NULL;
974		} else {
975			ctx->session_cache_tail = s->prev;
976			s->prev->next =
977			    (SSL_SESSION *)&(ctx->session_cache_tail);
978		}
979	} else {
980		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
981			/* first element in list */
982			ctx->session_cache_head = s->next;
983			s->next->prev =
984			    (SSL_SESSION *)&(ctx->session_cache_head);
985		} else {
986			/* middle of list */
987			s->next->prev = s->prev;
988			s->prev->next = s->next;
989		}
990	}
991	s->prev = s->next = NULL;
992}
993
994static void
995SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
996{
997	if ((s->next != NULL) && (s->prev != NULL))
998		SSL_SESSION_list_remove(ctx, s);
999
1000	if (ctx->session_cache_head == NULL) {
1001		ctx->session_cache_head = s;
1002		ctx->session_cache_tail = s;
1003		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1004		s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1005	} else {
1006		s->next = ctx->session_cache_head;
1007		s->next->prev = s;
1008		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1009		ctx->session_cache_head = s;
1010	}
1011}
1012
1013void
1014SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1015    int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1016	ctx->internal->new_session_cb = cb;
1017}
1018
1019int
1020(*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1021{
1022	return ctx->internal->new_session_cb;
1023}
1024
1025void
1026SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1027    void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1028{
1029	ctx->internal->remove_session_cb = cb;
1030}
1031
1032void
1033(*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1034{
1035	return ctx->internal->remove_session_cb;
1036}
1037
1038void
1039SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1040    unsigned char *data, int len, int *copy))
1041{
1042	ctx->internal->get_session_cb = cb;
1043}
1044
1045SSL_SESSION *
1046(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, unsigned char *data,
1047    int len, int *copy)
1048{
1049	return ctx->internal->get_session_cb;
1050}
1051
1052void
1053SSL_CTX_set_info_callback(SSL_CTX *ctx,
1054    void (*cb)(const SSL *ssl, int type, int val))
1055{
1056	ctx->internal->info_callback = cb;
1057}
1058
1059void
1060(*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1061{
1062	return ctx->internal->info_callback;
1063}
1064
1065void
1066SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1067    int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1068{
1069	ctx->internal->client_cert_cb = cb;
1070}
1071
1072int
1073(*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1074    EVP_PKEY **pkey)
1075{
1076	return ctx->internal->client_cert_cb;
1077}
1078
1079#ifndef OPENSSL_NO_ENGINE
1080int
1081SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1082{
1083	if (!ENGINE_init(e)) {
1084		SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1085		    ERR_R_ENGINE_LIB);
1086		return 0;
1087	}
1088	if (!ENGINE_get_ssl_client_cert_function(e)) {
1089		SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1090		    SSL_R_NO_CLIENT_CERT_METHOD);
1091		ENGINE_finish(e);
1092		return 0;
1093	}
1094	ctx->client_cert_engine = e;
1095	return 1;
1096}
1097#endif
1098
1099void
1100SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1101    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1102{
1103	ctx->internal->app_gen_cookie_cb = cb;
1104}
1105
1106void
1107SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1108    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len))
1109{
1110	ctx->internal->app_verify_cookie_cb = cb;
1111}
1112
1113int
1114PEM_write_SSL_SESSION(FILE *fp, SSL_SESSION *x)
1115{
1116	return PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION,
1117	    PEM_STRING_SSL_SESSION, fp, x, NULL, NULL, 0, NULL, NULL);
1118}
1119
1120SSL_SESSION *
1121PEM_read_SSL_SESSION(FILE *fp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1122{
1123	return PEM_ASN1_read((d2i_of_void *)d2i_SSL_SESSION,
1124	    PEM_STRING_SSL_SESSION, fp, (void **)x, cb, u);
1125}
1126
1127SSL_SESSION *
1128PEM_read_bio_SSL_SESSION(BIO *bp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1129{
1130	return PEM_ASN1_read_bio((d2i_of_void *)d2i_SSL_SESSION,
1131	    PEM_STRING_SSL_SESSION, bp, (void **)x, cb, u);
1132}
1133
1134int
1135PEM_write_bio_SSL_SESSION(BIO *bp, SSL_SESSION *x)
1136{
1137	return PEM_ASN1_write_bio((i2d_of_void *)i2d_SSL_SESSION,
1138	    PEM_STRING_SSL_SESSION, bp, x, NULL, NULL, 0, NULL, NULL);
1139}
1140