ssl_sess.c revision 1.107
1/* $OpenBSD: ssl_sess.c,v 1.107 2022/01/08 12:59:59 jsing Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2005 Nokia. All rights reserved.
113 *
114 * The portions of the attached software ("Contribution") is developed by
115 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116 * license.
117 *
118 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120 * support (see RFC 4279) to OpenSSL.
121 *
122 * No patent licenses or other rights except those expressly stated in
123 * the OpenSSL open source license shall be deemed granted or received
124 * expressly, by implication, estoppel, or otherwise.
125 *
126 * No assurances are provided by Nokia that the Contribution does not
127 * infringe the patent or other intellectual property rights of any third
128 * party or that the license provides you with all the necessary rights
129 * to make use of the Contribution.
130 *
131 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135 * OTHERWISE.
136 */
137
138#include <openssl/lhash.h>
139#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 minute timeout by default */
228	ss->time = time(NULL);
229	ss->prev = NULL;
230	ss->next = NULL;
231	ss->tlsext_hostname = NULL;
232
233	ss->peer_key = &ss->peer_pkeys[SSL_PKEY_RSA];
234
235	ss->tlsext_ecpointformatlist_length = 0;
236	ss->tlsext_ecpointformatlist = NULL;
237	ss->tlsext_supportedgroups_length = 0;
238	ss->tlsext_supportedgroups = NULL;
239
240	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
241
242	return (ss);
243}
244
245const unsigned char *
246SSL_SESSION_get_id(const SSL_SESSION *ss, unsigned int *len)
247{
248	if (len != NULL)
249		*len = ss->session_id_length;
250	return ss->session_id;
251}
252
253const unsigned char *
254SSL_SESSION_get0_id_context(const SSL_SESSION *ss, unsigned int *len)
255{
256	if (len != NULL)
257		*len = (unsigned int)ss->sid_ctx_length;
258	return ss->sid_ctx;
259}
260
261unsigned int
262SSL_SESSION_get_compress_id(const SSL_SESSION *ss)
263{
264	return 0;
265}
266
267unsigned long
268SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
269{
270	return s->tlsext_tick_lifetime_hint;
271}
272
273int
274SSL_SESSION_has_ticket(const SSL_SESSION *s)
275{
276	return (s->tlsext_ticklen > 0) ? 1 : 0;
277}
278
279/*
280 * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
281 * the ID with random gunk repeatedly until we have no conflict is going to
282 * complete in one iteration pretty much "most" of the time (btw:
283 * understatement). So, if it takes us 10 iterations and we still can't avoid
284 * a conflict - well that's a reasonable point to call it quits. Either the
285 * arc4random code is broken or someone is trying to open roughly very close to
286 * 2^128 (or 2^256) SSL sessions to our server. How you might store that many
287 * sessions is perhaps a more interesting question...
288 */
289
290#define MAX_SESS_ID_ATTEMPTS 10
291
292static int
293def_generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
294{
295	unsigned int retry = 0;
296
297	do {
298		arc4random_buf(id, *id_len);
299	} while (SSL_has_matching_session_id(ssl, id, *id_len) &&
300	    (++retry < MAX_SESS_ID_ATTEMPTS));
301
302	if (retry < MAX_SESS_ID_ATTEMPTS)
303		return 1;
304
305	/* else - woops a session_id match */
306	/* XXX We should also check the external cache --
307	 * but the probability of a collision is negligible, and
308	 * we could not prevent the concurrent creation of sessions
309	 * with identical IDs since we currently don't have means
310	 * to atomically check whether a session ID already exists
311	 * and make a reservation for it if it does not
312	 * (this problem applies to the internal cache as well).
313	 */
314	return 0;
315}
316
317int
318ssl_get_new_session(SSL *s, int session)
319{
320	unsigned int tmp;
321	SSL_SESSION *ss = NULL;
322	GEN_SESSION_CB cb = def_generate_session_id;
323
324	/* This gets used by clients and servers. */
325
326	if ((ss = SSL_SESSION_new()) == NULL)
327		return (0);
328
329	/* If the context has a default timeout, use it */
330	if (s->session_ctx->session_timeout == 0)
331		ss->timeout = SSL_get_default_timeout(s);
332	else
333		ss->timeout = s->session_ctx->session_timeout;
334
335	if (s->session != NULL) {
336		SSL_SESSION_free(s->session);
337		s->session = NULL;
338	}
339
340	if (session) {
341		switch (s->version) {
342		case TLS1_VERSION:
343		case TLS1_1_VERSION:
344		case TLS1_2_VERSION:
345		case DTLS1_VERSION:
346		case DTLS1_2_VERSION:
347			ss->ssl_version = s->version;
348			ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
349			break;
350		default:
351			SSLerror(s, SSL_R_UNSUPPORTED_SSL_VERSION);
352			SSL_SESSION_free(ss);
353			return (0);
354		}
355
356		/* If RFC4507 ticket use empty session ID. */
357		if (s->internal->tlsext_ticket_expected) {
358			ss->session_id_length = 0;
359			goto sess_id_done;
360		}
361
362		/* Choose which callback will set the session ID. */
363		CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
364		if (s->internal->generate_session_id)
365			cb = s->internal->generate_session_id;
366		else if (s->session_ctx->internal->generate_session_id)
367			cb = s->session_ctx->internal->generate_session_id;
368		CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
369
370		/* Choose a session ID. */
371		tmp = ss->session_id_length;
372		if (!cb(s, ss->session_id, &tmp)) {
373			/* The callback failed */
374			SSLerror(s, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
375			SSL_SESSION_free(ss);
376			return (0);
377		}
378
379		/*
380		 * Don't allow the callback to set the session length to zero.
381		 * nor set it higher than it was.
382		 */
383		if (!tmp || (tmp > ss->session_id_length)) {
384			/* The callback set an illegal length */
385			SSLerror(s, SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
386			SSL_SESSION_free(ss);
387			return (0);
388		}
389		ss->session_id_length = tmp;
390
391		/* Finally, check for a conflict. */
392		if (SSL_has_matching_session_id(s, ss->session_id,
393			ss->session_id_length)) {
394			SSLerror(s, SSL_R_SSL_SESSION_ID_CONFLICT);
395			SSL_SESSION_free(ss);
396			return (0);
397		}
398
399 sess_id_done:
400		if (s->tlsext_hostname) {
401			ss->tlsext_hostname = strdup(s->tlsext_hostname);
402			if (ss->tlsext_hostname == NULL) {
403				SSLerror(s, ERR_R_INTERNAL_ERROR);
404				SSL_SESSION_free(ss);
405				return 0;
406			}
407		}
408	} else {
409		ss->session_id_length = 0;
410	}
411
412	if (s->sid_ctx_length > sizeof ss->sid_ctx) {
413		SSLerror(s, ERR_R_INTERNAL_ERROR);
414		SSL_SESSION_free(ss);
415		return 0;
416	}
417
418	memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
419	ss->sid_ctx_length = s->sid_ctx_length;
420	s->session = ss;
421	ss->ssl_version = s->version;
422	ss->verify_result = X509_V_OK;
423
424	return (1);
425}
426
427static SSL_SESSION *
428ssl_session_from_cache(SSL *s, CBS *session_id)
429{
430	SSL_SESSION *sess;
431	SSL_SESSION data;
432
433	if ((s->session_ctx->internal->session_cache_mode &
434	     SSL_SESS_CACHE_NO_INTERNAL_LOOKUP))
435		return NULL;
436
437	memset(&data, 0, sizeof(data));
438
439	data.ssl_version = s->version;
440	data.session_id_length = CBS_len(session_id);
441	memcpy(data.session_id, CBS_data(session_id), CBS_len(session_id));
442
443	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
444	sess = lh_SSL_SESSION_retrieve(s->session_ctx->internal->sessions, &data);
445	if (sess != NULL)
446		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
447	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
448
449	if (sess == NULL)
450		s->session_ctx->internal->stats.sess_miss++;
451
452	return sess;
453}
454
455static SSL_SESSION *
456ssl_session_from_callback(SSL *s, CBS *session_id)
457{
458	SSL_SESSION *sess;
459	int copy;
460
461	if (s->session_ctx->internal->get_session_cb == NULL)
462		return NULL;
463
464	copy = 1;
465	if ((sess = s->session_ctx->internal->get_session_cb(s,
466	    CBS_data(session_id), CBS_len(session_id), &copy)) == NULL)
467		return NULL;
468	/*
469	 * The copy handler may have set copy == 0 to indicate that the session
470	 * structures are shared between threads and that it handles the
471	 * reference count itself. If it didn't set copy to zero, we must
472	 * increment the reference count.
473	 */
474	if (copy)
475		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
476
477	s->session_ctx->internal->stats.sess_cb_hit++;
478
479	/* Add the externally cached session to the internal cache as well. */
480	if (!(s->session_ctx->internal->session_cache_mode &
481	    SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
482		/*
483		 * The following should not return 1,
484		 * otherwise, things are very strange.
485		 */
486		SSL_CTX_add_session(s->session_ctx, sess);
487	}
488
489	return sess;
490}
491
492static SSL_SESSION *
493ssl_session_by_id(SSL *s, CBS *session_id)
494{
495	SSL_SESSION *sess;
496
497	if (CBS_len(session_id) == 0)
498		return NULL;
499
500	if ((sess = ssl_session_from_cache(s, session_id)) == NULL)
501		sess = ssl_session_from_callback(s, session_id);
502
503	return sess;
504}
505
506/*
507 * ssl_get_prev_session attempts to find an SSL_SESSION to be used to resume
508 * this connection. It is only called by servers.
509 *
510 *   session_id: points at the session ID in the ClientHello. This code will
511 *       read past the end of this in order to parse out the session ticket
512 *       extension, if any.
513 *   ext_block: a CBS for the ClientHello extensions block.
514 *   alert: alert that the caller should send in case of failure.
515 *
516 * Returns:
517 *   -1: error
518 *    0: a session may have been found.
519 *
520 * Side effects:
521 *   - If a session is found then s->session is pointed at it (after freeing
522 *     an existing session if need be) and s->verify_result is set from the
523 *     session.
524 *   - For both new and resumed sessions, s->internal->tlsext_ticket_expected
525 *     indicates whether the server should issue a new session ticket or not.
526 */
527int
528ssl_get_prev_session(SSL *s, CBS *session_id, CBS *ext_block, int *alert)
529{
530	SSL_SESSION *sess = NULL;
531	size_t session_id_len;
532	int alert_desc = SSL_AD_INTERNAL_ERROR, fatal = 0;
533	int ticket_decrypted = 0;
534
535	/* This is used only by servers. */
536
537	if (CBS_len(session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
538		goto err;
539
540	/* Sets s->internal->tlsext_ticket_expected. */
541	switch (tls1_process_ticket(s, ext_block, &alert_desc, &sess)) {
542	case TLS1_TICKET_FATAL_ERROR:
543		fatal = 1;
544		goto err;
545	case TLS1_TICKET_NONE:
546	case TLS1_TICKET_EMPTY:
547		if ((sess = ssl_session_by_id(s, session_id)) == NULL)
548			goto err;
549		break;
550	case TLS1_TICKET_NOT_DECRYPTED:
551		goto err;
552	case TLS1_TICKET_DECRYPTED:
553		ticket_decrypted = 1;
554
555		/*
556		 * The session ID is used by some clients to detect that the
557		 * ticket has been accepted so we copy it into sess.
558		 */
559		if (!CBS_write_bytes(session_id, sess->session_id,
560		    sizeof(sess->session_id), &session_id_len)) {
561			fatal = 1;
562			goto err;
563		}
564		sess->session_id_length = (unsigned int)session_id_len;
565		break;
566	default:
567		SSLerror(s, ERR_R_INTERNAL_ERROR);
568		fatal = 1;
569		goto err;
570	}
571
572	/* Now sess is non-NULL and we own one of its reference counts. */
573
574	if (sess->sid_ctx_length != s->sid_ctx_length ||
575	    timingsafe_memcmp(sess->sid_ctx, s->sid_ctx,
576	    sess->sid_ctx_length) != 0) {
577		/*
578		 * We have the session requested by the client, but we don't
579		 * want to use it in this context. Treat it like a cache miss.
580		 */
581		goto err;
582	}
583
584	if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
585		/*
586		 * We can't be sure if this session is being used out of
587		 * context, which is especially important for SSL_VERIFY_PEER.
588		 * The application should have used
589		 * SSL[_CTX]_set_session_id_context.
590		 *
591		 * For this error case, we generate an error instead of treating
592		 * the event like a cache miss (otherwise it would be easy for
593		 * applications to effectively disable the session cache by
594		 * accident without anyone noticing).
595		 */
596		SSLerror(s, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
597		fatal = 1;
598		goto err;
599	}
600
601	if (sess->cipher == NULL) {
602		sess->cipher = ssl3_get_cipher_by_id(sess->cipher_id);
603		if (sess->cipher == NULL)
604			goto err;
605	}
606
607	if (sess->timeout < (time(NULL) - sess->time)) {
608		s->session_ctx->internal->stats.sess_timeout++;
609		if (!ticket_decrypted) {
610			/* The session was from the cache, so remove it. */
611			SSL_CTX_remove_session(s->session_ctx, sess);
612		}
613		goto err;
614	}
615
616	s->session_ctx->internal->stats.sess_hit++;
617
618	SSL_SESSION_free(s->session);
619	s->session = sess;
620	s->verify_result = s->session->verify_result;
621
622	return 1;
623
624 err:
625	SSL_SESSION_free(sess);
626	if (ticket_decrypted) {
627		/*
628		 * The session was from a ticket. Issue a ticket for the new
629		 * session.
630		 */
631		s->internal->tlsext_ticket_expected = 1;
632	}
633	if (fatal) {
634		*alert = alert_desc;
635		return -1;
636	}
637	return 0;
638}
639
640int
641SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
642{
643	int ret = 0;
644	SSL_SESSION *s;
645
646	/*
647	 * Add just 1 reference count for the SSL_CTX's session cache
648	 * even though it has two ways of access: each session is in a
649	 * doubly linked list and an lhash.
650	 */
651	CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
652
653	/*
654	 * If session c is in already in cache, we take back the increment
655	 * later.
656	 */
657	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
658	s = lh_SSL_SESSION_insert(ctx->internal->sessions, c);
659
660	/*
661	 * s != NULL iff we already had a session with the given PID.
662	 * In this case, s == c should hold (then we did not really modify
663	 * ctx->internal->sessions), or we're in trouble.
664	 */
665	if (s != NULL && s != c) {
666		/* We *are* in trouble ... */
667		SSL_SESSION_list_remove(ctx, s);
668		SSL_SESSION_free(s);
669		/*
670		 * ... so pretend the other session did not exist in cache
671		 * (we cannot handle two SSL_SESSION structures with identical
672		 * session ID in the same cache, which could happen e.g. when
673		 * two threads concurrently obtain the same session from an
674		 * external cache).
675		 */
676		s = NULL;
677	}
678
679	/* Put at the head of the queue unless it is already in the cache */
680	if (s == NULL)
681		SSL_SESSION_list_add(ctx, c);
682
683	if (s != NULL) {
684		/*
685		 * existing cache entry -- decrement previously incremented
686		 * reference count because it already takes into account the
687		 * cache.
688		 */
689		SSL_SESSION_free(s); /* s == c */
690		ret = 0;
691	} else {
692		/*
693		 * New cache entry -- remove old ones if cache has become
694		 * too large.
695		 */
696
697		ret = 1;
698
699		if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
700			while (SSL_CTX_sess_number(ctx) >
701			    SSL_CTX_sess_get_cache_size(ctx)) {
702				if (!remove_session_lock(ctx,
703				    ctx->internal->session_cache_tail, 0))
704					break;
705				else
706					ctx->internal->stats.sess_cache_full++;
707			}
708		}
709	}
710	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
711	return (ret);
712}
713
714int
715SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
716{
717	return remove_session_lock(ctx, c, 1);
718}
719
720static int
721remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
722{
723	SSL_SESSION *r;
724	int ret = 0;
725
726	if ((c != NULL) && (c->session_id_length != 0)) {
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	} else
744		ret = 0;
745	return (ret);
746}
747
748void
749SSL_SESSION_free(SSL_SESSION *ss)
750{
751	int i;
752
753	if (ss == NULL)
754		return;
755
756	i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
757	if (i > 0)
758		return;
759
760	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
761
762	explicit_bzero(ss->master_key, sizeof ss->master_key);
763	explicit_bzero(ss->session_id, sizeof ss->session_id);
764
765	sk_X509_pop_free(ss->cert_chain, X509_free);
766	for (i = 0; i < SSL_PKEY_NUM; i++)
767		X509_free(ss->peer_pkeys[i].x509);
768
769	X509_free(ss->peer);
770
771	sk_SSL_CIPHER_free(ss->ciphers);
772
773	free(ss->tlsext_hostname);
774	free(ss->tlsext_tick);
775	free(ss->tlsext_ecpointformatlist);
776	free(ss->tlsext_supportedgroups);
777
778	freezero(ss, sizeof(*ss));
779}
780
781int
782SSL_SESSION_up_ref(SSL_SESSION *ss)
783{
784	int refs = CRYPTO_add(&ss->references, 1, CRYPTO_LOCK_SSL_SESSION);
785	return (refs > 1) ? 1 : 0;
786}
787
788int
789SSL_set_session(SSL *s, SSL_SESSION *session)
790{
791	const SSL_METHOD *method;
792
793	if (session == NULL) {
794		SSL_SESSION_free(s->session);
795		s->session = NULL;
796
797		return SSL_set_ssl_method(s, s->ctx->method);
798	}
799
800	if ((method = ssl_get_method(session->ssl_version)) == NULL) {
801		SSLerror(s, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
802		return (0);
803	}
804
805	if (!SSL_set_ssl_method(s, method))
806		return (0);
807
808	CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
809	SSL_SESSION_free(s->session);
810	s->session = session;
811	s->verify_result = s->session->verify_result;
812
813	return (1);
814}
815
816size_t
817SSL_SESSION_get_master_key(const SSL_SESSION *ss, unsigned char *out,
818    size_t max_out)
819{
820	size_t len = ss->master_key_length;
821
822	if (out == NULL)
823		return len;
824
825	if (len > max_out)
826		len = max_out;
827
828	memcpy(out, ss->master_key, len);
829
830	return len;
831}
832
833long
834SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
835{
836	if (s == NULL)
837		return (0);
838	s->timeout = t;
839	return (1);
840}
841
842long
843SSL_SESSION_get_timeout(const SSL_SESSION *s)
844{
845	if (s == NULL)
846		return (0);
847	return (s->timeout);
848}
849
850/* XXX 2038 */
851long
852SSL_SESSION_get_time(const SSL_SESSION *s)
853{
854	if (s == NULL)
855		return (0);
856	return (s->time);
857}
858
859/* XXX 2038 */
860long
861SSL_SESSION_set_time(SSL_SESSION *s, long t)
862{
863	if (s == NULL)
864		return (0);
865	s->time = t;
866	return (t);
867}
868
869int
870SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
871{
872	return s->ssl_version;
873}
874
875const SSL_CIPHER *
876SSL_SESSION_get0_cipher(const SSL_SESSION *s)
877{
878	return s->cipher;
879}
880
881X509 *
882SSL_SESSION_get0_peer(SSL_SESSION *s)
883{
884	return s->peer;
885}
886
887int
888SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
889    unsigned int sid_len)
890{
891	if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
892		SSLerrorx(SSL_R_SSL_SESSION_ID_TOO_LONG);
893		return 0;
894	}
895	s->session_id_length = sid_len;
896	memmove(s->session_id, sid, sid_len);
897	return 1;
898}
899
900int
901SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
902    unsigned int sid_ctx_len)
903{
904	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
905		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
906		return 0;
907	}
908	s->sid_ctx_length = sid_ctx_len;
909	memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
910
911	return 1;
912}
913
914int
915SSL_SESSION_is_resumable(const SSL_SESSION *s)
916{
917	return 0;
918}
919
920long
921SSL_CTX_set_timeout(SSL_CTX *s, long t)
922{
923	long l;
924
925	if (s == NULL)
926		return (0);
927	l = s->session_timeout;
928	s->session_timeout = t;
929
930	return (l);
931}
932
933long
934SSL_CTX_get_timeout(const SSL_CTX *s)
935{
936	if (s == NULL)
937		return (0);
938	return (s->session_timeout);
939}
940
941int
942SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s,
943    void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers,
944    SSL_CIPHER **cipher, void *arg), void *arg)
945{
946	if (s == NULL)
947		return (0);
948	s->internal->tls_session_secret_cb = tls_session_secret_cb;
949	s->internal->tls_session_secret_cb_arg = arg;
950	return (1);
951}
952
953int
954SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
955    void *arg)
956{
957	if (s == NULL)
958		return (0);
959	s->internal->tls_session_ticket_ext_cb = cb;
960	s->internal->tls_session_ticket_ext_cb_arg = arg;
961	return (1);
962}
963
964int
965SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
966{
967	if (s->version >= TLS1_VERSION) {
968		free(s->internal->tlsext_session_ticket);
969		s->internal->tlsext_session_ticket =
970		    malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
971		if (!s->internal->tlsext_session_ticket) {
972			SSLerror(s, ERR_R_MALLOC_FAILURE);
973			return 0;
974		}
975
976		if (ext_data) {
977			s->internal->tlsext_session_ticket->length = ext_len;
978			s->internal->tlsext_session_ticket->data =
979			    s->internal->tlsext_session_ticket + 1;
980			memcpy(s->internal->tlsext_session_ticket->data,
981			    ext_data, ext_len);
982		} else {
983			s->internal->tlsext_session_ticket->length = 0;
984			s->internal->tlsext_session_ticket->data = NULL;
985		}
986
987		return 1;
988	}
989
990	return 0;
991}
992
993typedef struct timeout_param_st {
994	SSL_CTX *ctx;
995	long time;
996	struct lhash_st_SSL_SESSION *cache;
997} TIMEOUT_PARAM;
998
999static void
1000timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
1001{
1002	if ((p->time == 0) || (p->time > (s->time + s->timeout))) {
1003		/* timeout */
1004		/* The reason we don't call SSL_CTX_remove_session() is to
1005		 * save on locking overhead */
1006		(void)lh_SSL_SESSION_delete(p->cache, s);
1007		SSL_SESSION_list_remove(p->ctx, s);
1008		s->not_resumable = 1;
1009		if (p->ctx->internal->remove_session_cb != NULL)
1010			p->ctx->internal->remove_session_cb(p->ctx, s);
1011		SSL_SESSION_free(s);
1012	}
1013}
1014
1015static void
1016timeout_LHASH_DOALL_ARG(void *arg1, void *arg2)
1017{
1018	SSL_SESSION *a = arg1;
1019	TIMEOUT_PARAM *b = arg2;
1020
1021	timeout_doall_arg(a, b);
1022}
1023
1024/* XXX 2038 */
1025void
1026SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1027{
1028	unsigned long i;
1029	TIMEOUT_PARAM tp;
1030
1031	tp.ctx = s;
1032	tp.cache = s->internal->sessions;
1033	if (tp.cache == NULL)
1034		return;
1035	tp.time = t;
1036	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1037	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
1038	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
1039	lh_SSL_SESSION_doall_arg(tp.cache, timeout_LHASH_DOALL_ARG,
1040	TIMEOUT_PARAM, &tp);
1041	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
1042	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1043}
1044
1045int
1046ssl_clear_bad_session(SSL *s)
1047{
1048	if ((s->session != NULL) && !(s->internal->shutdown & SSL_SENT_SHUTDOWN) &&
1049	    !(SSL_in_init(s) || SSL_in_before(s))) {
1050		SSL_CTX_remove_session(s->ctx, s->session);
1051		return (1);
1052	} else
1053		return (0);
1054}
1055
1056/* locked by SSL_CTX in the calling function */
1057static void
1058SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1059{
1060	if (s->next == NULL || s->prev == NULL)
1061		return;
1062
1063	if (s->next == (SSL_SESSION *)&(ctx->internal->session_cache_tail)) {
1064		/* last element in list */
1065		if (s->prev == (SSL_SESSION *)&(ctx->internal->session_cache_head)) {
1066			/* only one element in list */
1067			ctx->internal->session_cache_head = NULL;
1068			ctx->internal->session_cache_tail = NULL;
1069		} else {
1070			ctx->internal->session_cache_tail = s->prev;
1071			s->prev->next =
1072			    (SSL_SESSION *)&(ctx->internal->session_cache_tail);
1073		}
1074	} else {
1075		if (s->prev == (SSL_SESSION *)&(ctx->internal->session_cache_head)) {
1076			/* first element in list */
1077			ctx->internal->session_cache_head = s->next;
1078			s->next->prev =
1079			    (SSL_SESSION *)&(ctx->internal->session_cache_head);
1080		} else {
1081			/* middle of list */
1082			s->next->prev = s->prev;
1083			s->prev->next = s->next;
1084		}
1085	}
1086	s->prev = s->next = NULL;
1087}
1088
1089static void
1090SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1091{
1092	if (s->next != NULL && s->prev != NULL)
1093		SSL_SESSION_list_remove(ctx, s);
1094
1095	if (ctx->internal->session_cache_head == NULL) {
1096		ctx->internal->session_cache_head = s;
1097		ctx->internal->session_cache_tail = s;
1098		s->prev = (SSL_SESSION *)&(ctx->internal->session_cache_head);
1099		s->next = (SSL_SESSION *)&(ctx->internal->session_cache_tail);
1100	} else {
1101		s->next = ctx->internal->session_cache_head;
1102		s->next->prev = s;
1103		s->prev = (SSL_SESSION *)&(ctx->internal->session_cache_head);
1104		ctx->internal->session_cache_head = s;
1105	}
1106}
1107
1108void
1109SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1110    int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1111	ctx->internal->new_session_cb = cb;
1112}
1113
1114int
1115(*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1116{
1117	return ctx->internal->new_session_cb;
1118}
1119
1120void
1121SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1122    void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1123{
1124	ctx->internal->remove_session_cb = cb;
1125}
1126
1127void
1128(*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1129{
1130	return ctx->internal->remove_session_cb;
1131}
1132
1133void
1134SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1135    const unsigned char *data, int len, int *copy))
1136{
1137	ctx->internal->get_session_cb = cb;
1138}
1139
1140SSL_SESSION *
1141(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, const unsigned char *data,
1142    int len, int *copy)
1143{
1144	return ctx->internal->get_session_cb;
1145}
1146
1147void
1148SSL_CTX_set_info_callback(SSL_CTX *ctx,
1149    void (*cb)(const SSL *ssl, int type, int val))
1150{
1151	ctx->internal->info_callback = cb;
1152}
1153
1154void
1155(*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1156{
1157	return ctx->internal->info_callback;
1158}
1159
1160void
1161SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1162    int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1163{
1164	ctx->internal->client_cert_cb = cb;
1165}
1166
1167int
1168(*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1169    EVP_PKEY **pkey)
1170{
1171	return ctx->internal->client_cert_cb;
1172}
1173
1174#ifndef OPENSSL_NO_ENGINE
1175int
1176SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1177{
1178	if (!ENGINE_init(e)) {
1179		SSLerrorx(ERR_R_ENGINE_LIB);
1180		return 0;
1181	}
1182	if (!ENGINE_get_ssl_client_cert_function(e)) {
1183		SSLerrorx(SSL_R_NO_CLIENT_CERT_METHOD);
1184		ENGINE_finish(e);
1185		return 0;
1186	}
1187	ctx->internal->client_cert_engine = e;
1188	return 1;
1189}
1190#endif
1191
1192void
1193SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1194    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1195{
1196	ctx->internal->app_gen_cookie_cb = cb;
1197}
1198
1199void
1200SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1201    int (*cb)(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len))
1202{
1203	ctx->internal->app_verify_cookie_cb = cb;
1204}
1205
1206int
1207PEM_write_SSL_SESSION(FILE *fp, SSL_SESSION *x)
1208{
1209	return PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION,
1210	    PEM_STRING_SSL_SESSION, fp, x, NULL, NULL, 0, NULL, NULL);
1211}
1212
1213SSL_SESSION *
1214PEM_read_SSL_SESSION(FILE *fp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1215{
1216	return PEM_ASN1_read((d2i_of_void *)d2i_SSL_SESSION,
1217	    PEM_STRING_SSL_SESSION, fp, (void **)x, cb, u);
1218}
1219
1220SSL_SESSION *
1221PEM_read_bio_SSL_SESSION(BIO *bp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1222{
1223	return PEM_ASN1_read_bio((d2i_of_void *)d2i_SSL_SESSION,
1224	    PEM_STRING_SSL_SESSION, bp, (void **)x, cb, u);
1225}
1226
1227int
1228PEM_write_bio_SSL_SESSION(BIO *bp, SSL_SESSION *x)
1229{
1230	return PEM_ASN1_write_bio((i2d_of_void *)i2d_SSL_SESSION,
1231	    PEM_STRING_SSL_SESSION, bp, x, NULL, NULL, 0, NULL, NULL);
1232}
1233