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