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