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